11

我有一个使用 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)

我见过的所有刷新示例都涉及一个oauth2对象(例如oauth.refresh_access_token()),并且文档仅列出了该函数作为刷新令牌的方法。据我了解,使用授权代码流,您不需要oauth对象(因为您使用 进行身份验证prompt_for_user_token())。如果是这种情况,我该如何刷新我的令牌?

4

1 回答 1

11

我的 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)
于 2018-03-14T18:35:40.997 回答