Spotipy Refreshing a token with authorization code flow

前端 未结 1 564
滥情空心
滥情空心 2021-02-15 09:11

I have a long-running script using spotipy. After an hour (per the Spotify API), my access token expires. I am catching this successfully, but I don\'t know where to go from the

相关标签:
1条回答
  • 2021-02-15 10:01

    After receiving no response on 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.

    Their example for Authorization Code flow uses prompt_for_user_token().

    I switched to the OAuth approach, which is a pain because it requires re-authorization every time I run the program (really only a problem while I was testing but a problem nonetheless). Since there are no examples of OAuth2 in the Spotipy docs, I'll paste mine here.

    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)
    

    To refresh my token (required every hour), I use this function. When and where you call it depends on your program.

    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)
    
    0 讨论(0)
提交回复
热议问题