0

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

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

我该如何解决?

4

1 回答 1

0

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

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
于 2017-03-12T05:55:10.083 回答