简体   繁体   English

适用于Python的Google Analytics(分析)Reporting API入门

[英]Getting started with Google Analytics Reporting API for Python

I am just starting with the Google Analytics Reporting API and used the Hello API tutorial to get started. 我只是从Google Analytics(分析)Reporting API入手,并使用Hello API教程进行入门。 ( https://developers.google.com/analytics/solutions/articles/hello-analytics-api ) https://developers.google.com/analytics/solutions/articles/hello-analytics-api

Unfortunately, I am stuck before I even start. 不幸的是,我在开始之前就被困住了。 I read it (twice). 我读了两次。 Created the project, updates the client_secrets.jason file... but when I run the main, it crashes. 创建了项目,更新了client_secrets.jason文件...但是当我运行主文件时,它崩溃了。

  File "C:\Python27\New Libraries Downloaded\analytics-v3-python-cmd-line\hello_analytics_api_v3.py", line 173, in <module>
    main(sys.argv)
  File "C:\Python27\New Libraries Downloaded\analytics-v3-python-cmd-line\hello_analytics_api_v3.py", line 56, in main
    service, flags = sample_tools.init(argv, 'analytics', 'v3', __doc__, __file__, scope='https://www.googleapis.com/auth/analytics.readonly')
NameError: global name '__file__' is not defined

I'm new (really really new) to this, so any help (and a more detailed tutorial) would be much appreciated. 我是这个新手(真的很新),所以任何帮助(以及更详细的教程)将不胜感激。

Thanks ! 谢谢 !

EDIT: I have't changed anything from the original code in the tutorial. 编辑:我没有改变教程中原始代码的任何内容。 I'll worry about modifications after I get this running. 运行此命令后,我将担心修改。 Thanks ! 谢谢 !

CODE: hello_analytics_api_v3.py 代码:hello_analytics_api_v3.py

import argparse
import sys

from apiclient.errors import HttpError
from apiclient import sample_tools
from oauth2client.client import AccessTokenRefreshError


def main(argv):
  # Authenticate and construct service.
  service, flags = sample_tools.init(argv, 'analytics', 'v3', __doc__, __file__, scope='https://www.googleapis.com/auth/analytics.readonly')

  # Try to make a request to the API. Print the results or handle errors.
  try:
    first_profile_id = get_first_profile_id(service)
    if not first_profile_id:
      print 'Could not find a valid profile for this user.'
    else:
      results = get_top_keywords(service, first_profile_id)
      print_results(results)

  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 ('Arg, there was an API error : %s : %s' % (error.resp.status, error._get_reason()))

  except AccessTokenRefreshError:
    # Handle Auth errors.
    print ('The credentials have been revoked or expired, please re-run ','the application to re-authorize')


def get_first_profile_id(service):
  """Traverses Management API to return the first profile id.

  This first queries the Accounts collection to get the first account ID.
  This ID is used to query the Webproperties collection to retrieve the first
  webproperty ID. And both account and webproperty IDs are used to query the
  Profile collection to get the first profile id.

  Args:
    service: The service object built by the Google API Python client library.

  Returns:
    A string with the first profile ID. None if a user does not have any
    accounts, webproperties, or profiles.
  """

  accounts = service.management().accounts().list().execute()

  if accounts.get('items'):
    firstAccountId = accounts.get('items')[0].get('id')
    webproperties = service.management().webproperties().list(
        accountId=firstAccountId).execute()

    if webproperties.get('items'):
      firstWebpropertyId = webproperties.get('items')[0].get('id')
      profiles = service.management().profiles().list(
          accountId=firstAccountId,
          webPropertyId=firstWebpropertyId).execute()

      if profiles.get('items'):
        return profiles.get('items')[0].get('id')

  return None


def get_top_keywords(service, profile_id):
  """Executes and returns data from the Core Reporting API.

  This queries the API for the top 25 organic search terms by visits.

  Args:
    service: The service object built by the Google API Python client library.
    profile_id: String The profile ID from which to retrieve analytics data.

  Returns:
    The response returned from the Core Reporting API.
  """

  return service.data().ga().get(
      ids='ga:' + profile_id,
      start_date='2012-01-01',
      end_date='2012-01-15',
      metrics='ga:visits',
      dimensions='ga:source,ga:keyword',
      sort='-ga:visits',
      filters='ga:medium==organic',
      start_index='1',
      max_results='25').execute()


def print_results(results):
  """Prints out the results.

  This prints out the profile name, the column headers, and all the rows of
  data.

  Args:
    results: The response returned from the Core Reporting API.
  """

  print
  print 'Profile Name: %s' % results.get('profileInfo').get('profileName')
  print

  # Print header.
  output = []
  for header in results.get('columnHeaders'):
    output.append('%30s' % header.get('name'))
  print ''.join(output)

  # Print data table.
  if results.get('rows', []):
    for row in results.get('rows'):
      output = []
      for cell in row:
        output.append('%30s' % cell)
      print ''.join(output)

  else:
    print 'No Rows Found'


if __name__ == '__main__':
  main(sys.argv)

according to the error the program doesn't recognize ' file '. 根据错误,程序无法识别“ 文件 ”。 In IPython this error comes up (not 100% sure why) but this error shouldn't come up when running a file. 在IPython中会出现此错误(不是100%确定原因),但是在运行文件时不应出现此错误。 In a file the ' file ' argument will return the full path and the file name. 在文件中,“ file ”参数将返回完整路径和文件名。

Try creating a file and running from there or simply paste in a the full path and file name instead. 尝试创建一个文件并从那里运行,或者只是粘贴完整的路径和文件名。

Also be sure that the client secrets are located in the same folder as your script! 另外,请确保客户端机密与脚本位于同一文件夹中!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM