Created
September 23, 2014 19:29
-
-
Save harperreed/f37a56949f0e06bd1ed1 to your computer and use it in GitHub Desktop.
easily use access token and refresh token with gspread
This file contains 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
import gspread | |
from oauth2client.client import OAuth2Credentials | |
import datetime | |
import requests | |
class OAuthGspread: | |
scope = ['https://spreadsheets.google.com/feeds', 'https://docs.google.com/feeds'] | |
def __init__(self, client_id, client_secret, access_token, refresh_token, ): | |
self.oauth_params = dict( | |
client_id=client_id, | |
client_secret=client_secret, | |
access_type='offline' | |
) | |
self.oauth_creds = { | |
"access_token": access_token, | |
"refresh_token": refresh_token | |
} | |
self.refresh_params = { | |
'client_id': self.oauth_params['client_id'], | |
'refresh_token': self.oauth_creds['refresh_token'], | |
'client_secret': self.oauth_params['client_secret'], | |
'grant_type': 'refresh_token' | |
} | |
def gspread(self): | |
credentials = self.oauth_credentials() | |
gc = gspread.authorize(credentials) | |
return gc | |
def oauth_credentials(self): | |
rs = requests.post('https://accounts.google.com/o/oauth2/token', self.refresh_params).json() | |
expiry = datetime.datetime.now() + datetime.timedelta(seconds=rs['expires_in']) | |
cred_params = { | |
'access_token': rs['access_token'], | |
'client_id': self.oauth_params['client_id'], | |
'client_secret': self.oauth_params['client_secret'], | |
'refresh_token': self.refresh_params['refresh_token'], | |
'token_expiry': expiry, | |
'token_uri': 'https://accounts.google.com/o/oauth2/token', | |
'user_agent': '', | |
} | |
return OAuth2Credentials(**cred_params) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment