如何从GA-api-v4获取两个以上的日期范围值?

时间:2019-01-28 09:00:15

标签: python api google-analytics-api

我发现在广泛的日期范围内每天的唯一用户价值。 根据GA用户的定义,当您选择较宽的日期范围时,唯一身份用户将受到影响。 例如,在日期范围介于2018-01-01至2018-12-31之间搜索“ 2018-01-01”用户,输出为10000,但仅在“ 2018-01-01”至“ 2018-01-01”之间进行搜索11000。

我发现我们可以在GA-api-v4上设置多个日期范围,但最多只能提供2个日期范围。我希望我能得到如下所示的宽日期范围结果:

class GA(object):
    def __init__(self):

        #GA Setting
        self.SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
        self.KEY_FILE_LOCATION = 'xxx.json'
        self.service = self.initialize_analyticsreporting()

    def initialize_analyticsreporting(self):
  """Initializes an Analytics Reporting API V4 service object.
  Returns:
    An authorized Analytics Reporting API V4 service object.
  """
      credentials = ServiceAccountCredentials.from_json_keyfile_name(
      self.KEY_FILE_LOCATION, self.SCOPES)
  # Build the service object.
      analytics = build('analyticsreporting', 'v4', credentials=credentials)
  return analytics

    def get_user(self):
  """Queries the Analytics Reporting API V4.

  Args:
    analytics: An authorized Analytics Reporting API V4 service object.
  Returns:
    The Analytics Reporting API V4 response.
  """

      analytics = self.initialize_analyticsreporting()
      import datetime, calendar
      year = 2018
      month = 1
      num_days = calendar.monthrange(year, month)[1]
      days = [datetime.date(year, month, day) for day in range(1, num_days+1)]
      dates =  [datetime.datetime.strftime(x, '%Y-%m-%d')  for x in days]
      return analytics.reports().batchGet(
          body={
        'reportRequests': [
        {
          'viewId': 'ga:12345678',
          'dateRanges': [{'startDate': date, 'endDate': date} for date in dates]],
          'metrics': [{'expression': "ga:users", 'alias' :'users'}],
          'dimensions': [{'name': 'ga:date'}]]
        }
        ]
      }
  ).execute()
    def print_response(self, 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)

要获取结果:

get = GA()
response = get.user()
get.print_response(response)

我想避免长时间循环以重复连接GA服务) 如何方便地获得相同的结果?

0 个答案:

没有答案