oauth2client устарел - PullRequest
       50

oauth2client устарел

0 голосов
/ 04 апреля 2019

В коде Python для запроса данных из Google Analytics (https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-py) через API используется oauth2client.Последний раз код обновлялся в июле 2018 года, и до сих пор 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.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...