在我的 github 问题上没有收到任何回复后,在我看来,如果不使用 OAuth2,就无法刷新令牌。这违背了 Spotipy 文档中的说明:
授权码流程:此方法适用于用户登录一次的长时间运行的应用程序。它提供了一个可以刷新的访问令牌。
他们的授权代码流示例使用 prompt_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)
为了刷新我的令牌(每小时需要一次),我使用了这个函数。您何时何地调用它取决于您的程序。
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)