3

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!

aevumcessi
  • 61
  • 8
  • You need to store and use refresh tokens for long-lasting OAuth2 access, described in the [Authorization Code Flow](https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow) section of the Spotify API Authorization docs – Rach Sharp Apr 16 '19 at 09:16

1 Answers1

0

You can use the memory cache handler from the spotipy library to store the acess token in memory instead of the disk: https://github.com/plamere/spotipy/blob/master/spotipy/cache_handler.py

You can also take a look at the example flask app in the examples directory: https://github.com/plamere/spotipy/blob/master/examples/app.py

  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/31749567) – James Barnett May 16 '22 at 15:18