【发布时间】:2019-05-13 01:01:42
【问题描述】:
我正在构建一个简单的应用程序来学习 Python 3 和 Flask。目标是使用来自 Spotify API 的数据,为此我需要使用 OAuth 2.0 进行身份验证。
我可以向 Spotify 帐户提供我的凭据,但是在回调期间发生了以下错误:
File "app.py", line 59, in callback
access_token = response_data["access_token"]
KeyError: 'access_token'
代码示例:
post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload, headers=headers)
response_data = json.loads(post_request.text)
access_token = response_data["access_token"]
token_type = response_data["token_type"]
expires_in = response_data["expires_in"]
refresh_token = response_data["refresh_token"]
这是来自API documentation 的请求响应示例:
{
"access_token": "NgCXRK...MzYjw",
"token_type": "Bearer",
"scope": "user-read-private user-read-email",
"expires_in": 3600,
"refresh_token": "NgAagA...Um_SHo"
}
我很迷茫。不确定它是否与 API 响应内容有关,或者应用程序如何使用 json.loads(post_request.text) 解析它。
编辑:获得 HTTP 状态代码后,我能够对问题有所了解:
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://accounts.spotify.com/api/token
但是我仍然无法弄清楚我的请求有什么问题:
authentication_token = request.args['code']
code_payload = {
"grant_type": "authorization_code",
"code": str(authentication_token),
"redirect_uri": REDIRECT_URI
}
encoded_oauth2_tokens = base64.b64encode('{}:{}'.format(CLIENT_ID, CLIENT_SECRET).encode())
headers = {"Authorization": "Basic {}".format(encoded_oauth2_tokens)}
post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload, headers=headers)
post_request.raise_for_status()
【问题讨论】:
-
来自
b64encode文档:使用 Base64 对字节类对象进行编码并返回编码后的字节。在创建标头时尝试调用encoded_oauth2_tokens.decode()。此外,您应该在code_payload中包含范围。 -
不需要范围,我的错
-
@HarrySky 你明白了! .decode() 成功了。非常感谢!
标签: python-3.x flask oauth-2.0 spotify restful-authentication