我有一个长时间运行的脚本使用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()),而docs列表仅作为刷新令牌的一种方法。我的理解是,使用授权代码流,您不需要oauth对象(因为您使用prompt_for_user_token()进行身份验证)。如果是这样的话,我如何刷新我的令牌?
发布于 2018-03-14 18:35:40
在我的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)发布于 2022-07-20 20:30:10
我认为,当涉及到这个问题时,有问题的文档是有误导性的。
我花了一些时间试图解决这个问题。以前也有人问过类似的问题:链接在这里
我发现这个问题的答案是非常有用的,并将其概括如下:函数util.prompt_user_for_token()可以被回收并返回一个令牌,而不需要被提示重新授权(给出一个输入,如您看到的解决方案)。我认为这就是为什么spotipy文档声称它可以自己“刷新”的原因。但在现实中,需要一些提示。
例如,我在这里的项目中采用了与您的解决方案类似的解决方案:
def refresh_token():
token = spotipy.util.prompt_for_user_token(user_id, scopes)
last_refresh = datetime.now()
return {'token': token, 'last_refresh': last_refresh}我只需根据last_refresh时间(以一个小时为限)调用此函数。
我希望这能有所帮助,抱歉,如果没有用的话。
https://stackoverflow.com/questions/49239516
复制相似问题