现在不建议使用oauth2client

时间:2019-04-04 13:52:06

标签: python credentials google-auth-library requests-oauthlib

在用于通过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.

1 个答案:

答案 0 :(得分:1)

对于遇到此问题并希望移植到较新的身份验证库的用户,请在code repo上对{{3 }},以查看需要更新的内容(以及可以保持原样的内容)。底线是,API客户端库代码可以保持不变,而您所做的只是交换下面的身份验证库。

请注意,该示例仅适用于 user acct auth ...,适用于 svc acct auth ,但更新与此类似,但我尚无该示例(不过,正在开发中……将在发布后对其进行更新)。