How to get Google Analytics credentials without gflags - using run_flow() instead? How to get Google Analytics credentials without gflags - using run_flow() instead? python python

How to get Google Analytics credentials without gflags - using run_flow() instead?


from oauth2client import toolsflags = tools.argparser.parse_args(args=[])credentials = tools.run_flow(flow, storage, flags)

Took a bit of mucking about but climbed my way out the two traps it dropped me into:

  1. have to use the argparser provided in tools
  2. I had to feed args an empty list to prevent it from reading args off the command line, which was a problem because I'm running it from inside a unittest (so different cmdline args).


This piece of code works for me for the gmail api.

(Also this link helped. Command-line tools)

import argparseimport httplib2from oauth2client.tools import run_flowfrom oauth2client.tools import argparserfrom oauth2client.file import StorageCLIENT_SECRETS_FILE = "your_file.json"OAUTH_SCOPE = 'https://www.googleapis.com/auth/gmail.readonly'STORAGE = Storage("storage")flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope=OAUTH_SCOPE)http = httplib2.Http()credentials = STORAGE.get()if credentials is None or credentials.invalid:    #magic     parser = argparse.ArgumentParser(parents=[argparser])    flags = parser.parse_args()    credentials = run_flow(flow, STORAGE, flags, http=http)http = credentials.authorize(http)gmApi = build('gmail', 'v1', http=http)# ...


The flags that can be passed can be found here and are:

  --auth_host_name: Host name to use when running a local web server    to handle redirects during OAuth authorization.    (default: 'localhost')  --auth_host_port: Port to use when running a local web server to handle    redirects during OAuth authorization.;    repeat this option to specify a list of values    (default: '[8080, 8090]')    (an integer)  --[no]auth_local_webserver: Run a local web server to handle redirects    during OAuth authorization.    (default: 'true')

I have yet to work out how exactly to parse them, I have tried passing through various different values for each of these three flags but nothing works for me. I have a bountied question here that may be of use for you when answered.