Spotify OAuth 2.0 callback python



我按照spotify文档通过WEB API ....进行身份验证使用下面的代码,我可以获得访问授权

import requests
endpoint_auth = 'https://accounts.spotify.com/authorize'
redirect_uri = 'http://localhost:8888/spotify/index.html'
client_id = '1234567890'
scope = "playlist-modify-private"
params_auth = {
"response_type": "code",
"client_id": client_id,
"scope": scope,
"redirect_uri": redirect_uri,
}
response_auth = requests.get(url=endpoint_auth, params=params_auth)
print(response_auth.status_code)
print(response_auth.text)

第一次打印是ok的响应200第二次打印给我页面html的内容登录如果我把内容保存在doc html中并打开文件给出一个错误但如果我组成url路径并从浏览器启动它,如"https://accounts.spotify.com/authorize?response_type=code&client_id=1234567890&redirect_uri=http://localhost:8888/spotify/index.html&scope=playlist-modify-private"响应在回调页面(http://localhost:8888/spotify/index.html?code=23u2344u123u4u1)中发送给我,并向get....中的url添加CODE参数这是请求访问令牌的参数。

我的问题是:有可能在我发出请求后读取url回调,所以我打印response_auth。文本打印回调url与参数代码?

您可以使用管理它的requests_oauthlib库,参见https://requests-oauthlib.readthedocs.io/en/latest/examples/spotify.html

#First set the client_id/client_secret/redirect_uri
#authorization_base_url, token_url & scope
from requests_oauthlib import OAuth2Session
spotify = OAuth2Session(client_id, scope=scope, redirect_uri=redirect_uri)
# Redirect user to Spotify for authorization
authorization_url, state = spotify.authorization_url(authorization_base_url)
print('Please go here and authorize: ', authorization_url)
# Get the authorization verifier code from the callback url
redirect_response = input('nnPaste the full redirect URL here: ')
from requests.auth import HTTPBasicAuth
auth = HTTPBasicAuth(client_id, client_secret)
# Fetch the access token
token = spotify.fetch_token(token_url, auth=auth,
authorization_response=redirect_response)
print(token)
# Fetch a protected resource, i.e. user profile
r = spotify.get('https://api.spotify.com/v1/me')
print(r.content)

最新更新