KeyError异常:使用Spotify的API OAuth 2.0验证期间 'ACCESS

2019-11-05 08:38发布

我建立一个简单的应用程序来学习Python 3瓶。 我们的目标是为使用来自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文档 :

{
   "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()

Answer 1:

你确定你实际上是从Spotify的网络API获取数据,而不是错误响应?

这是我使用和它运作良好

@dataclass
class Tokens:
    access: str
    refresh: str
    expires_at: int

# Class that sets up authorization_headers
# Class method
def get_tokens(self, code_from_redirect_uri: str) -> bool:
        payload: dict = {'redirect_uri': self._redirect_uri, 'code': code_from_redirect_uri,
                        'grant_type': 'authorization_code', 'scope': self._scope}
        response: Response = post(OAUTH_TOKEN_URL, data=payload, headers=self.authorization_headers)
        # When we don't get the OK response - we assume code was bad
        if response.status_code != 200:
            return False

        token_info: dict = response.json()
        self.tokens = Tokens(token_info['access_token'], token_info['refresh_token'], token_info['expires_in']*1000 + time())
        return True


文章来源: KeyError: 'access_token' during OAuth 2.0 authentication using Spotify API