Search code examples
pythonpython-2.7google-analyticsgoogle-analytics-api

Finding out where analytics should be defined


I am working with Google Analytics api in python and keep getting the error

NameError: name 'analytics' is not defined. 

I have been searching for several days on the analytics api site and on StackOverflow for the answer. If someone could please point me in the direction of the right documentation or help me out here that would be greatly appreciated. Attached is the code that I have so far.

from apiclient.http import MediaFileUpload
from apiclient.errors import HttpError

try:
  media = MediaFileUpload('Bing_Ad_Test.csv',
                          mimetype='application/octet-stream',
                          resumable=False)
  daily_upload = analytics.management().uploads().uploadData(
      accountId='',
      webPropertyId='',
      customDataSourceId='',
      media_body=media).execute()

except TypeError, error:
  # Handle errors in constructing a query.
  print 'There was an error in constructing your query : %s' % error

except HttpError, error:
  # Handle API errors.
  print ('There was an API error : %s : %s' %
         (error.resp.status, error.resp.reason))

Solution

  • The error is saying what is happening: you did not define the name analytics used in line 9 previously

    daily_upload = analytics.management().uploads().uploadData(
    

    You need to go over the first steps in order to use that and import it. You will also need an account since it requires auth.

    https://developers.google.com/analytics/devguides/reporting/core/v3/quickstart/service-py

    After you setup, you should read

    https://developers.google.com/analytics/devguides/reporting/core/v3/coreDevguide

    With that you should be ok!