Spotipy Refreshing a token with authorization code flow

让人想犯罪 __ 提交于 2019-12-04 11:23:52

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!