Spotify授权代码-获取令牌[控制台应用程序]

时间:2018-08-07 14:28:48

标签: python spotify spotipy

我正在编写一个控制台应用程序,根据歌曲列表在Spotify上创建播放列表。我正在使用Spotipy,并尝试使用util.prompt_for_user_token(),问题是在授予访问权限后,我必须手动将重定向链接粘贴到控制台中。

User authentication requires interaction with your
    web browser. Once you enter your credentials and
    give authorization, you will be redirected to
    a url.  Paste that url you were directed to to
    complete the authorization.

有没有办法使这个过程自动化? here解决方案对我没有帮助

1 个答案:

答案 0 :(得分:0)

prompt_for_user_token函数是Spotipy提供的某些功能的简写。这是函数本身的代码。

https://github.com/plamere/spotipy/blob/master/spotipy/util.py

[ -- snip -- ]

def prompt_for_user_token(username, scope=None, client_id = None,
    client_secret = None, redirect_uri = None, cache_path = None):
''' prompts the user to login if necessary and returns
    the user token suitable for use with the spotipy.Spotify 
    constructor
    Parameters:
     - username - the Spotify username
     - scope - the desired scope of the request
     - client_id - the client id of your app
     - client_secret - the client secret of your app
     - redirect_uri - the redirect URI of your app
     - cache_path - path to location to save tokens
'''

[ -- snip -- ]

cache_path = cache_path or ".cache-" + username
sp_oauth = oauth2.SpotifyOAuth(client_id, client_secret, redirect_uri, 
    scope=scope, cache_path=cache_path)

[ -- snip -- ]

token_info = sp_oauth.get_cached_token()

if not token_info:
    print('''
        User authentication requires interaction with your
        web browser. Once you enter your credentials and
        give authorization, you will be redirected to
        a url.  Paste that url you were directed to to
        complete the authorization.
    ''')
    auth_url = sp_oauth.get_authorize_url()
    try:
        import webbrowser
        webbrowser.open(auth_url)
        print("Opened %s in your browser" % auth_url)
    except:
        print("Please navigate here: %s" % auth_url)

[ -- snip -- ]

您可以复制代码,并在auth_url模块和popen中使用chrome.exe(例如),并以auth_url作为参数。

提示:在Windows cmd.exe /c start http://your.website/address下,会将地址转发到您当前的默认浏览器。 (与对firefox.exechrome.exe进行硬编码相反)