Created
May 8, 2014 03:20
-
-
Save aliafshar/3402d5b86b47d3a200e7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # The following 2 lines should never be seen together. Yet here they are. | |
| import httplib2 | |
| import requests | |
| class CredentialsAuthorizer(requests.auth.AuthBase): | |
| """Uses oauth2client credentials to authorize requests requests.""" | |
| #: How many times we will retry a request that might need refreshing | |
| retries = 3 | |
| #: Response codes that will trigger | |
| refresh_codes = (401,) | |
| def __init__(self, credentials): | |
| self.credentials = credentials | |
| self.retries = 1 | |
| self.httplib2client = httplib2.Http() | |
| def handle_response(self, response, **kw): | |
| """Called for every response from requests. | |
| We check if the response has one of the special refresh statuses, and if the | |
| credentials are suitable, a refresh will be attempted, and the original | |
| request retried. | |
| """ | |
| if self.credentials.refresh_token and response.status_code == 401 and self.retries: | |
| self.credentials.refresh(self.httplib2client) | |
| self.retries -= 1 | |
| response.request.send(anyway=True) | |
| return response.response | |
| else: | |
| return response | |
| def __call__(self, request): | |
| """Called for every request. | |
| We register the response callback, and inject the authorization header. | |
| """ | |
| request.register_hook('response', self.handle_response) | |
| request.headers['Authorization'] = 'Bearer {}'.format( | |
| self.credentials.access_token) | |
| return request | |
| def test(): | |
| from oauth2client.client import AccessTokenCredentials | |
| creds = AccessTokenCredentials( | |
| 'ACCESS TOKEN REMOVED', | |
| '') | |
| auth = CredentialsAuthorizer(creds) | |
| r = requests.get('https://www.googleapis.com/drive/v2/about', auth=auth) | |
| print r.json()['name'] | |
| r = requests.get('https://www.googleapis.com/drive/v2/files', auth=auth) | |
| print len(r.json()['items']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment