Spotipy使用授权代码刷新令牌

2024-04-26 07:46:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个使用spotipy的长期运行脚本。一小时后(根据spotifyapi),我的访问令牌将过期。我成功地捕捉到了这个,但是我不知道从那里到哪里才能真正刷新令牌。我使用的是授权代码流,而不是客户端凭据。以下是我如何授权:

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()),而docs只列出了一个刷新令牌的方法。我的理解是,使用授权代码流,您不需要oauth对象(因为您使用prompt_for_user_token()进行身份验证)。如果是这样,我如何刷新我的令牌?在


Tags: 对象代码脚本clienttokenidforsecret
1条回答
网友
1楼 · 发布于 2024-04-26 07:46:49

在没有收到对my github issue的响应之后,我觉得不使用OAuth2就无法刷新令牌。这与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方法,这很痛苦,因为每次运行程序时都需要重新授权(实际上这只是我测试时的问题,但仍然是个问题)。由于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)

为了刷新我的令牌(每小时需要一次),我使用这个函数。你何时何地调用它取决于你的程序。在

^{pr2}$

相关问题 更多 >