gos*_*gos 5 python authorization refresh spotipy
我有一个使用Spotipy的长时间运行的脚本。一个小时后(根据Spotify API),我的访问令牌失效。我已经成功地捕获了该令牌,但是在实际刷新令牌方面我不知道从那里可以走。我使用的是授权码流程,而不是客户端凭据。这是我的授权方式:
token = util.prompt_for_user_token(username,scope=scopes,client_id=client_id,client_secret=client_secret, redirect_uri=redirect_uri)
sp = spotipy.Spotify(auth=token)
Run Code Online (Sandbox Code Playgroud)
我见过的所有刷新示例都涉及一个oauth2
对象(例如oauth.refresh_access_token()
),并且docs仅列出该对象作为刷新令牌的方法。据我了解,通过授权代码流,您不需要一个oauth
对象(因为您使用进行了身份验证prompt_for_user_token()
)。如果是这种情况,我该如何刷新令牌?
在我的github问题上没有收到任何响应之后,在我看来,如果不使用OAuth2,就无法刷新令牌。这违背了Spotipy文档中的规定:
授权代码流:此方法适用于用户一次登录的长时间运行的应用程序。它提供了可以刷新的访问令牌。
他们的授权码流程示例使用了hint_for_user_token()。
我切换到OAuth方法,这很痛苦,因为每次运行程序时都需要重新授权(这确实是我在测试时遇到的问题,但仍然是问题)。由于Spotipy文档中没有OAuth2的示例,因此我将其粘贴在此处。
sp_oauth = oauth2.SpotifyOAuth(client_id=client_id,client_secret=client_secret,redirect_uri=redirect_uri,scope=scopes)
token_info = sp_oauth.get_cached_token()
if not token_info:
auth_url = sp_oauth.get_authorize_url(show_dialog=True)
print(auth_url)
response = input('Paste the above link into your browser, then paste the redirect url here: ')
code = sp_oauth.parse_response_code(response)
token_info = sp_oauth.get_access_token(code)
token = token_info['access_token']
sp = spotipy.Spotify(auth=token)
Run Code Online (Sandbox Code Playgroud)
要刷新我的令牌(每小时需要一次),我使用此功能。调用的时间和地点取决于您的程序。
def refresh():
global token_info, sp
if sp_oauth.is_token_expired(token_info):
token_info = sp_oauth.refresh_access_token(token_info['refresh_token'])
token = token_info['access_token']
sp = spotipy.Spotify(auth=token)
Run Code Online (Sandbox Code Playgroud)