I haven't robustly tested this, but it works for testing snippets with my personal account. I'm sure there are changes that could and/or should be made to it for enterprise applications, such as passing auth'd Http()
instances, detecting scope changes, and so on.
You can review the full code on my GitHub repo:
requirements:
- google-api-python-client
- google-auth
- google-auth-oauthlib
- whatever deps the above pull in
I use the InstalledAppFlow
class, and generally followed the instructions on Google's Python auth guide.
Code (Python 3.6)
# Google API imports
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
SCOPES = ['your scopes', 'here']
def get_saved_credentials(filename='creds.json'):
'''Read in any saved OAuth data/tokens
'''
fileData = {}
try:
with open(filename, 'r') as file:
fileData: dict = json.load(file)
except FileNotFoundError:
return None
if fileData and 'refresh_token' in fileData and 'client_id' in fileData and 'client_secret' in fileData:
return Credentials(**fileData)
return None
def store_creds(credentials, filename='creds.json'):
if not isinstance(credentials, Credentials):
return
fileData = {'refresh_token': credentials.refresh_token,
'token': credentials.token,
'client_id': credentials.client_id,
'client_secret': credentials.client_secret,
'token_uri': credentials.token_uri}
with open(filename, 'w') as file:
json.dump(fileData, file)
print(f'Credentials serialized to {filename}.')
def get_credentials_via_oauth(filename='client_secret.json', scopes=SCOPES, saveData=True) -> Credentials:
'''Use data in the given filename to get oauth data
'''
iaflow: InstalledAppFlow = InstalledAppFlow.from_client_secrets_file(filename, scopes)
iaflow.run_local_server()
if saveData:
store_creds(iaflow.credentials)
return iaflow.credentials
def get_service(credentials, service='sheets', version='v4'):
return build(service, version, credentials=credentials)
Usage is then:
creds = get_saved_credentials()
if not creds:
creds = get_credentials_via_oauth()
sheets = get_service(creds)