【问题标题】:Issues with sample HelloAnalytics.py from Analytics Reporting API v4Analytics Reporting API v4 中的示例 HelloAnalytics.py 的问题
【发布时间】:2020-06-17 06:48:57
【问题描述】:

official Quickstart Webpage 上的 Google 的 sample code 已过时且无法使用。

作为Google encourages to use StackOverflow,我不仅希望在以下问题上得到帮助,还希望激励 Google 更新他们的示例代码

  • 我 pip 安装了 google-api-python-client(没有 sudo,btw)。

  • 不再有SERVICE_ACCOUNT_EMAIL (for years)。

  • 作为KEY_FILE_LOCATION,我输入了 JSON 文件的名称。这就是您所说的“来自开发者控制台的适当值”吗?

  • 我修复了第 65、68 和 70 行中的打印函数(这也是 confused others,特别是因为 Python 2.7 是 deprecated 用于 google-api-python-client)。

如果我运行它,我会收到以下错误:

Traceback (most recent call last):
  File "/Users/ralf/code/test_snippets/20-06-17_google_analytics_api/HelloAnalytics.py", line 4, in <module>
    from oauth2client.service_account import ServiceAccountCredentials
ModuleNotFoundError: No module named 'oauth2client'

很明显,缺少导入。 oauth2client 已弃用,他们推荐 google-authoauthlib

我怎样才能让它工作?欢迎任何提示,请 Google 修复该示例代码,以免其他人进行令人沮丧和乏味的研究。

谢谢!

【问题讨论】:

  • 您链接的服务帐户是已安装应用程序的帐户吗? developers.google.com/analytics/devguides/reporting/core/v4/…我已经 ping 团队关于需要更新的样本感谢报告。
  • 我的 google 联系人再次表示感谢,请留意新版本应该会在明天上线
  • 很抱歉再次打扰您,但据我所知there仍然是网上的旧版本。请您再次询问您的联系人好吗?非常感谢!

标签: python google-api google-analytics-api google-api-python-client


【解决方案1】:

Google 现已更新示例代码(感谢DaImTo),如下所示:

"""Hello Analytics Reporting API V4."""

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials


SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
KEY_FILE_LOCATION = '<REPLACE_WITH_JSON_FILE>'
VIEW_ID = '<REPLACE_WITH_VIEW_ID>'


def initialize_analyticsreporting():
  """Initializes an Analytics Reporting API V4 service object.

  Returns:
    An authorized Analytics Reporting API V4 service object.
  """
  credentials = ServiceAccountCredentials.from_json_keyfile_name(
      KEY_FILE_LOCATION, SCOPES)

  # Build the service object.
  analytics = build('analyticsreporting', 'v4', credentials=credentials)

  return analytics


def get_report(analytics):
  """Queries the Analytics Reporting API V4.

  Args:
    analytics: An authorized Analytics Reporting API V4 service object.
  Returns:
    The Analytics Reporting API V4 response.
  """
  return analytics.reports().batchGet(
      body={
        'reportRequests': [
        {
          'viewId': VIEW_ID,
          'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],
          'metrics': [{'expression': 'ga:sessions'}],
          'dimensions': [{'name': 'ga:country'}]
        }]
      }
  ).execute()


def print_response(response):
  """Parses and prints the Analytics Reporting API V4 response.

  Args:
    response: An Analytics Reporting API V4 response.
  """
  for report in response.get('reports', []):
    columnHeader = report.get('columnHeader', {})
    dimensionHeaders = columnHeader.get('dimensions', [])
    metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])

    for row in report.get('data', {}).get('rows', []):
      dimensions = row.get('dimensions', [])
      dateRangeValues = row.get('metrics', [])

      for header, dimension in zip(dimensionHeaders, dimensions):
        print(header + ': ', dimension)

      for i, values in enumerate(dateRangeValues):
        print('Date range:', str(i))
        for metricHeader, value in zip(metricHeaders, values.get('values')):
          print(metricHeader.get('name') + ':', value)


def main():
  analytics = initialize_analyticsreporting()
  response = get_report(analytics)
  print_response(response)

if __name__ == '__main__':
  main()

不幸的是,我仍然收到错误:

Exception has occurred: HttpError
<HttpError 403 when requesting https://analyticsreporting.googleapis.com/v4/reports:batchGet?alt=json returned "User does not have sufficient permissions for this profile.">
  File "/Users/ralf/code/test_snippets/20-07-01_google_analytics_api/HelloAnalytics.py", line 42, in get_report
    'dimensions': [{'name': 'ga:country'}]
  File "/Users/ralf/code/test_snippets/20-07-01_google_analytics_api/HelloAnalytics.py", line 75, in main
    response = get_report(analytics)
  File "/Users/ralf/code/test_snippets/20-07-01_google_analytics_api/HelloAnalytics.py", line 80, in <module>
    main()

我仔细按照here 所述的步骤进行操作,尤其是Create CredentialsAdd service account to the Google Analytics account,但显然出了点问题。我稍后会再试一次。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-01
    • 2017-09-26
    • 1970-01-01
    • 1970-01-01
    • 2016-11-22
    • 2021-03-12
    • 2016-08-19
    相关资源
    最近更新 更多