예제 #1
0
    def make_request(self, url, data={}, method=None, **kwargs):
        """
        Builds and makes the OAuth Request, catches errors

        https://wiki.fitbit.com/display/API/API+Response+Format+And+Errors
        """
        if not method:
            method = 'POST' if data else 'GET'
        auth = OAuth1(self.client_key,
                      self.client_secret,
                      self.resource_owner_key,
                      self.resource_owner_secret,
                      signature_type='auth_header')
        response = self._request(method, url, data=data, auth=auth, **kwargs)

        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
예제 #2
0
    def test_auto_refresh_token_exception(self):
        """Test of auto_refresh with Unauthorized exception"""
        # 1. first call to _request causes a HTTPUnauthorized
        # 2. the token_refresh call is faked
        # 3. the second call to _request returns a valid value
        kwargs = self.client_kwargs
        kwargs['access_token'] = 'fake_access_token'
        kwargs['refresh_token'] = 'fake_refresh_token'

        fb = Fitbit(**kwargs)
        with mock.patch.object(FitbitOauth2Client, '_request') as r:
            r.side_effect = [
                HTTPUnauthorized(fake_response(401, b'correct_response')),
                fake_response(200, 'correct_response')
            ]
            with mock.patch.object(OAuth2Session, 'refresh_token') as rt:
                rt.return_value = {
                    'access_token': 'fake_return_access_token',
                    'refresh_token': 'fake_return_refresh_token'
                }
                retval = fb.client.make_request(Fitbit.API_ENDPOINT +
                                                '/1/user/-/profile.json')
        self.assertEqual("correct_response", retval.text)
        self.assertEqual("fake_return_access_token",
                         fb.client.token['access_token'])
        self.assertEqual("fake_return_refresh_token",
                         fb.client.token['refresh_token'])
        self.assertEqual(1, rt.call_count)
        self.assertEqual(2, r.call_count)
예제 #3
0
    def make_request(self, url, data={}, method=None, **kwargs):
        """
        Builds and makes the Oauth Request, catches errors

        https://wiki.fitbit.com/display/API/API+Response+Format+And+Errors
        """
        if not method:
            method = 'POST' if data else 'GET'
        headers = kwargs.pop('headers', {})
        request = oauth.Request.from_consumer_and_token(self._consumer,
                                                        self._token,
                                                        http_method=method,
                                                        http_url=url,
                                                        parameters=data)
        request.sign_request(self._signature_method, self._consumer,
                             self._token)
        headers.update(request.to_header())
        response = self._request(method, url, data=data, headers=headers)

        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 >= 500:
            raise HTTPServerError(response)
        elif response.status_code >= 400:
            raise HTTPBadRequest(response)
        return response
예제 #4
0
    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 TokenExpiredError 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']=='oauth' and
                    d['errors'][0]['fieldName']=='access_token' and
                    d['errors'][0]['message'].find('Access token invalid or 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