问题
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.
回答1:
The rough process that Spotipy takes with access tokens is:
- Get the token from the cache (is actually more than just access token, also refresh and expiry date info)
- If token was in the cache and has expired, refresh it
- 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.
来源:https://stackoverflow.com/questions/48883731/refresh-token-spotipy