0

在通过 API 从 Google Analytics( https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-py )请求数据的 Python 代码中,使用了 oauth2client。该代码最后一次更新是在 2018 年 7 月,直到现在 oauth2client 已被弃用。我的问题是我可以获得相同的代码,而不是使用 oauth2client、google-auth 或 oauthlib 吗?

我正在谷歌上搜索如何替换正在使用 oauth2client 的代码部分的解决方案。然而,由于我不是开发人员,所以我没有成功。这就是我尝试将此链接(https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-py)中的代码调整为google-auth的方式。知道如何解决这个问题吗?

import argparse

from apiclient.discovery import build
from google.oauth2 import service_account
from google.auth.transport.urllib3 import AuthorizedHttp


SCOPES = ['...']
DISCOVERY_URI = ('...')
CLIENT_SECRETS_PATH = 'client_secrets.json' # Path to client_secrets.json file.
VIEW_ID = '...'


def initialize_analyticsreporting():
  """Initializes the analyticsreporting service object.

  Returns:l
    analytics an authorized analyticsreporting service object.
  """
  # Parse command-line arguments.
  credentials = service_account.Credentials.from_service_account_file(CLIENT_SECRETS_PATH)


  # Prepare credentials, and authorize HTTP object with them.
  # If the credentials don't exist or are invalid run through the native client
  # flow. The Storage object will ensure that if successful the good
  # credentials will get written back to a file.
authed_http = AuthorizedHttp(credentials)

response = authed_http.request(
    'GET', SCOPES)

  # Build the service object.
  analytics = build('analytics', 'v4', http=http, discoveryServiceUrl=DISCOVERY_URI)

  return analytics

def get_report(analytics):
  # Use the Analytics Service Object to query the Analytics Reporting API V4.
  return analytics.reports().batchGet(
      body=
    {
    "reportRequests":[
    {
      "viewId":VIEW_ID,
      "dateRanges":[
      {
        "startDate":"2019-01-01",
        "endDate":"yesterday"
      }],
      "dimensions":[
      {
        "name":"ga:transactionId"
      },
      {
        "name":"ga:sourceMedium"
      },
      {
        "name":"ga:date"
      }],
      "metrics":[
      {
        "expression":"ga:transactionRevenue"
      }]
    }]
  }
).execute()


def printResults(response):
  for report in response.get("reports", []):
    columnHeader = report.get("columnHeader", {})
    dimensionHeaders = columnHeader.get("dimensions", [])
    metricHeaders = columnHeader.get("metricHeader", {}).get("metricHeaderEntries", [])
    rows = report.get("data", {}).get("rows", [])

    for row in 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):
        for metric, value in zip(metricHeaders, values.get("values")):
          print (metric.get("name") + ": " + value)


def main():

  analytics = initialize_analyticsreporting()
  response = get_report(analytics)
  printResults(response)

if __name__ == '__main__':
  main()

I need to obtain response in form of a json with given dimensions and metrics from Google Analytics.
4

1 回答 1

1

对于那些遇到此问题并希望移植到较新的身份验证库的人,请在G Suite API 介绍代码实验室的代码仓库中对 2 个不同版本的简短/简单 Google Drive API 示例进行比较,以查看需要什么要更新(以及可以保持原样的内容)。底线是 API 客户端库代码可以保持不变,而您所做的只是换掉下面的身份验证库。

请注意,示例仅适用于用户 acct auth ......对于svc acct auth,更新类似,但我还没有一个示例(虽然正在研究一个......将在发布后更新)。

于 2020-03-28T01:27:06.553 回答