-
-
Save AnjaneyuluBatta505/db442547b4c49839133b12ab3ba5e0bf to your computer and use it in GitHub Desktop.
How to get Google OAuth 2.0 access token in console using the Python API
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
#!/usr/bin/env python | |
''' | |
This script will attempt to open your webbrowser, | |
perform OAuth 2.0 authentication and print your access token. | |
To install dependencies from PyPI: | |
$ pip install oauth2client | |
Then run this script: | |
$ python get_oauth2_token.py | |
This is a combination of snippets from: | |
https://developers.google.com/api-client-library/python/guide/aaa_oauth | |
https://gist.github.com/burnash/6771295 | |
''' | |
import os, sys | |
from oauth2client.client import OAuth2WebServerFlow | |
from oauth2client.tools import run_flow | |
from oauth2client.file import Storage | |
def return_token(): | |
return get_oauth2_token(); | |
def disable_stout(): | |
o_stdout = sys.stdout | |
o_file = open(os.devnull, 'w') | |
sys.stdout = o_file | |
return (o_stdout, o_file) | |
def enable_stout(o_stdout, o_file): | |
o_file.close() | |
sys.stdout = o_stdout | |
def get_oauth2_token(): | |
CLIENT_ID = '<Client ID from Google API Console>' | |
CLIENT_SECRET = '<Client secret from Google API Console>' | |
SCOPE = '<OAuth 2.0 scope>' | |
REDIRECT_URI = '<Redirect URI from Google API Console>' | |
o_stdout, o_file = disable_stout() | |
flow = OAuth2WebServerFlow( | |
client_id=CLIENT_ID, | |
client_secret=CLIENT_SECRET, | |
scope=SCOPE, | |
redirect_uri=REDIRECT_URI) | |
storage = Storage('creds.data') | |
credentials = run_flow(flow, storage) | |
enable_stout(o_stdout, o_file) | |
print "access_token: %s" % credentials.access_token | |
if __name__ == '__main__': | |
return_token() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment