问题
I'm trying to use Spotipy to access a user's Spotify library but am running into a bit of trouble. For background, I'm using Flask, SQLAlchemy, and Flask-Login.
I looked off of this tutorial on github to get started, but this one doesn't quite work for me because if you use a cache, all users can access the playlist of the user whose token is cached, and since there is a cached token, any user after the first user can't login to Spotify. Here is some initial setup:
sp_oauth = oauth2.SpotifyOAuth(os.environ['SPOTIPY_CLIENT_ID'],
os.environ['SPOTIPY_CLIENT_SECRET'],
os.environ['SPOTIPY_REDIRECT_URI'],
scope="user-library-read")
To solve this, I first tried storing each user's access code in my database (I'm using SQLAlchemy as well). It looked something like this (under the method for the page that Spotipy redirects to with the access code):
if request.args.get("code"):
dbsession.query(User).get(current_user.uid).addService(
request.args["code"])
dbsession.commit()
However, this route is meant to return the names of the playlists the user owns, so I want it to be accessible without having to go through the Spotify authorization URL every time as long as the user is logged in. So, in the case where request.args["code"]
is null, I try:
token_info = sp_oauth.get_access_token(dbsession.query(User)
.get(current_user.uid)
.getService())
spotify = spotipy.Spotify(token_info["access_token"])
Then I try to access the user using this instance of Spotify. However, using the stored access code (unsurprisingly) gives me a Bad Request error. I'm not sure what to do about getting a new code, or what I should store so that I don't need to cache but can still get credentials to access the playlists. Alternatively, is there a way that I can cache but only have certain users access certain tokens in the cache?
Thanks!
来源:https://stackoverflow.com/questions/40571136/having-trouble-using-cached-tokens-with-spotipy-for-spotify