Last active
May 25, 2019 03:58
-
-
Save kunanit/de44ee056bfcad75214a62004806848e to your computer and use it in GitHub Desktop.
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
from google.oauth2 import service_account | |
from google_auth_oauthlib.flow import InstalledAppFlow | |
def get_oauth2_credentials(client_secrets_file, port=5555, scopes=SCOPES): | |
""" | |
Get google credentials via oauth flow | |
Opens up a browser for user to sign in | |
Requires client secrets file (select application type = 'other' when creating client in google console) | |
Sets default local web server port to 5555, since 8080 not usually available locally, but port can be specified as | |
an arg, for example if you are already using port 5555 for something | |
:param client_secrets_file: (str) location of client secrets file (e.g. '/path/to/file.json`) | |
:param port: port to use for local webserver to listen on for auth response | |
:param scopes: (list) auth scope, e.g. ['https://www.googleapis.com/auth/drive'] | |
:return: (google.oauth2.credentials.Credentials) google credentials object | |
""" | |
flow = InstalledAppFlow.from_client_secrets_file( | |
client_secrets_file, | |
scopes=scopes) | |
return flow.run_local_server(port=port) | |
def get_service_account_credentials(credential_file=None, scopes=SCOPES): | |
""" | |
Get credentials using a service account credential file | |
Supports retrieving credential file location from GOOGLE_APPLICATION_CREDENTIALS env variable | |
:param credential_file: (str) location of service account credential file (e.g. '/path/to/file.json`) | |
:param scopes: (list) auth scope, e.g. ['https://www.googleapis.com/auth/drive'] | |
:return: (google.auth.service_account.Credentials) google credentials object | |
""" | |
if not credential_file: | |
credential_file = os.environ.get('GOOGLE_APPLICATION_CREDENTIALS') | |
if not credential_file: | |
raise Exception("Service account file not found (Is GOOGLE_APPLICATION_CREDENTIALS env var set?)") | |
return service_account.Credentials.from_service_account_file(credential_file, scopes=scopes) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment