api.py 文件源码

python
阅读 20 收藏 0 点赞 0 评论 0

项目:Fitbit 作者: jaromirsalamon 项目源码 文件源码
def make_request(self, url, data={}, method=None, **kwargs):
        """
        Builds and makes the OAuth2 Request, catches errors

        https://wiki.fitbit.com/display/API/API+Response+Format+And+Errors
        """
        if not method:
            method = 'POST' if data else 'GET'

        try:
            auth = OAuth2(client_id=self.client_id, token=self.token)
            response = self._request(method, url, data=data, auth=auth, **kwargs)
        except HTTPUnauthorized as e:
            self.refresh_token()
            auth = OAuth2(client_id=self.client_id, token=self.token)
            response = self._request(method, url, data=data, auth=auth, **kwargs)

        # yet another token expiration check
        # (the above try/except only applies if the expired token was obtained
        # using the current instance of the class this is a a general case)
        if response.status_code == 401:
            d = json.loads(response.content.decode('utf8'))
            try:
                if(d['errors'][0]['errorType'] == 'expired_token' and
                    d['errors'][0]['message'].find('Access token expired:') == 0):
                        self.refresh_token()
                        auth = OAuth2(client_id=self.client_id, token=self.token)
                        response = self._request(method, url, data=data, auth=auth, **kwargs)
            except:
                pass

        if response.status_code == 401:
            raise HTTPUnauthorized(response)
        elif response.status_code == 403:
            raise HTTPForbidden(response)
        elif response.status_code == 404:
            raise HTTPNotFound(response)
        elif response.status_code == 409:
            raise HTTPConflict(response)
        elif response.status_code == 429:
            exc = HTTPTooManyRequests(response)
            exc.retry_after_secs = int(response.headers['Retry-After'])
            raise exc

        elif response.status_code >= 500:
            raise HTTPServerError(response)
        elif response.status_code >= 400:
            raise HTTPBadRequest(response)
        return response
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号