【问题标题】:Spotipy Refreshing a token with authorization code flowSpotipy 使用授权代码流刷新令牌
【发布时间】:2018-08-20 17:25:39
【问题描述】:

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

【问题讨论】:

    标签: python authorization refresh spotipy


    【解决方案1】:

    my github issue 上没有收到任何回复后,在我看来,如果不使用 OAuth2,就无法刷新令牌。这与the Spotipy docs 中的规定背道而驰:

    授权码流程:此方法适用于用户登录一次的长时间运行的应用程序。 它提供了一个可以刷新的访问令牌。

    他们的授权代码流程示例使用 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)
    

    【讨论】:

      猜你喜欢
      • 2020-12-13
      • 2014-10-31
      • 2017-05-01
      • 2018-08-21
      • 2021-02-26
      • 2022-11-27
      • 2016-12-10
      • 2021-07-01
      • 1970-01-01
      相关资源
      最近更新 更多