j0nes j0nes - 2 years ago 694
Python Question

Google Analytics API access without local browser in python

I want to query the Google Analytics API using Python to periodically download data from my Analytics account and store data in a local database. I am basically following the steps as given in the basic tutorial. I am using the Google client API library for Python in this process.

My script is working fine so far when I am running it on my local dev machine (Mac). When I start the script, my browser opens and I am prompted to grant access to my Analytics data from the app. Afterwards I can run my script as often as I want and get access to my data.

On my server (Ubuntu, only terminal available), the

browser opens, but I cannot access my Google account from there. I can only quit
and kill the program with
. There is an error message like:

Your browser has been opened to visit:


If your browser is on a different machine then exit and re-run this
application with the command-line parameter


However when I run my script with the parameter
, I get the same results -
opens and I cannot authenticate.

How can I get the
to work? I there another way to authenticate without a local browser on the same machine?

Answer Source

When you use FLAGS = gflags.FLAGS, you actually need to pass the command-line arguments to FLAGS (this may or may not have tripped me up as well :) ). See here for an Analytics-centric example of how to do it (code below as links tend to go away after a while). General idea is that argv arguments are passed into the FLAGS variable, which then become available to other modules.

# From samples/analytics/sample_utils.py in the google-api-python-client source

def process_flags(argv):
  """Uses the command-line flags to set the logging level.

    argv: List of command line arguments passed to the python script.

  # Let the gflags module process the command-line arguments.
    argv = FLAGS(argv)
  except gflags.FlagsError, e:
    print '%s\nUsage: %s ARGS\n%s' % (e, argv[0], FLAGS)

  # Set the logging according to the command-line flag.
  logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))

Also, turns out that we aren't alone! You can track this bug to see when this will get added the documentation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download