Spotify API - 通过命令行进行身份验证

Spotify API - authentication via command line

为了访问我的播放列表,我使用了从 spotipy documentation 页面获得的以下示例代码:

import pprint
import sys
import os
import subprocess

import spotipy
import spotipy.util as util


client_id = 'my_id'
client_secret = 'my_secret'
redirect_uri = 'http://localhost:8000/callback/'

scope = 'user-library-read'

if len(sys.argv) > 1:
    username = sys.argv[1]
else:
    print "Usage: %s username" % (sys.argv[0],)
    sys.exit()

token = util.prompt_for_user_token(username, scope, client_id, client_secret, redirect_uri)

if token:
    sp = spotipy.Spotify(auth=token)
    results = sp.current_user_saved_tracks()
    for item in results['items']:
        track = item['track']
        print track['name'] + ' - ' + track['artists'][0]['name']
else:
    print "Can't get token for", username

当我 运行 使用 python myscript.py myusername 的脚本时,我得到了这个:

     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.


Opening https://accounts.spotify.com/authorize?scope=user-library-read&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fcallback&response_type=code&client_id=d3b2f7a12362468daa393cf457185973 in your browser


Enter the URL you were redirected to:

然后,如果我输入 http://localhost:8000/callback/,我会得到以下错误:

token = util.prompt_for_user_token(username, scope, client_id, client_secret, redirect_uri)
  File "/Library/Python/2.7/site-packages/spotipy/util.py", line 86, in prompt_for_user_token
    token_info = sp_oauth.get_access_token(code)
  File "/Library/Python/2.7/site-packages/spotipy/oauth2.py", line 210, in get_access_token
    raise SpotifyOauthError(response.reason)
spotipy.oauth2.SpotifyOauthError: Bad Request

我该如何解决这个问题?

我运行同样的示例代码和运行一样的问题。但是首先通过 运行 本地主机上的服务器 python -m SimpleHTTPServer 让它工作,然后使我的应用程序的网站 http://localhost:8000 和我的重定向 http://localhost:8000 也一样。之后我打开了一个新终端 window 和 运行 python myscript.py my_user_name url 然后在我的浏览器中打开如果它没有为你打开,你可以复制并粘贴url link 它从终端的这一行给了你

Opening https://accounts.spotify.com/authorize?scope=user-library-read&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fcallback&response_type=code&client_id=d3b2f7a12362468daa393cf457185973 in your browser

直接进入您的浏览器,您会看到一个页面,要求您授予该应用访问您帐户的权限。执行此操作后,您应该在终端中复制并粘贴的新 url 将直接出现在浏览器中。之后你不会看到任何事情发生,因为你需要打印令牌:

token = util.prompt_for_user_token(
    username, scope, client_id, client_secret, redirect_uri)

if token:
  print "token: ", token
  sp = spotipy.Spotify(auth=token)
  # code 
else:
  print "Can't get token for", username