Spotipy 使用授权代码流刷新令牌

Spotipy Refreshing a token with authorization code flow

我有一个使用 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() 进行身份验证)。如果是这样,我该如何刷新我的令牌?

my github issue, it appears to me that there's no way to refresh a token without using OAuth2. This goes against what is stated in the Spotipy docs 上没有收到回复:

The Authorization Code flow: This method is suitable for long-running applications which the user logs into once. It provides an access token that can be refreshed.

他们的授权代码流程示例使用 prompt_for_user_token()。

我切换到 OAuth 方法,这很痛苦,因为每次我 运行 程序时它都需要 re-authorization(这只是我测试时的一个问题,但仍然是一个问题)。由于 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)