Having trouble using cached tokens with Spotipy for Spotify?

好久不见. 提交于 2021-02-07 04:18:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!