Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refresh token spotipy

I am using spotipy to retrieve some tracks from Spotify using python. I get a token expiration error thus, I want to refresh my token. But I don't understand how to get the refresh token from spotipy.

Is there another way to refresh the token or recreate one?

Thank you.

like image 383
mina Avatar asked Feb 20 '18 11:02

mina


1 Answers

The rough process that Spotipy takes with access tokens is:

  1. Get the token from the cache (is actually more than just access token, also refresh and expiry date info)
  2. If token was in the cache and has expired, refresh it
  3. If token wasn't in the cache, then prompt_for_user_token() will handle you completing the OAuth flow in browser, after which it will save it to the cache.

So it will be refreshed automatically if you ask Spotipy for your access token (e.g. with prompt_for_user_token() or by setting up a SpotifyOAuth object directly) and it has cached the access token / refresh token previously. Cache location should be .cache-<username> in the working directory by default, so you can access the tokens manually there.


If you provide the Spotipy Spotify() client with auth param for authorization, it will not be able to refresh the access token automatically and I think it will expire after about an hour. You can provide it a client_credentials_manager instead, which it will request the access token from. The only requirement of an implementation of the client_credentials_manager object is that it provides a get_access_token() method which takes no params and returns an access token.

I tried this out in a fork a while back, here's the modification to the SpotifyOAuth object to allow it to act as a client_credentials_manager and here's the equivalent of prompt_for_user_token() that returns the SpotifyOAuth object that you can pass to Spotipy Spotify() client as a credentials manager param.

like image 123
Rach Sharp Avatar answered Oct 19 '22 22:10

Rach Sharp