Python 谷歌分析获取视图I';d使用API

Python 谷歌分析获取视图I';d使用API,python,google-analytics,Python,Google Analytics,我正在尝试构建一个支持分析工具,它将允许最终用户使用来自多个来源的数据创建自己的仪表板,其中一个来源是Google analytics。我使用谷歌分析核心报告API获取数据。但是现在,我正在手动插入我的用户帐户的视图来获取数据。因为我是为最终用户构建它的,所以当他们使用oauth授权我的应用程序时,我需要能够以编程方式(使用API)获取用户帐户的视图。我见过像databox这样的工具,它们已经实现了这一点,所以我想知道如何复制相同的功能。下面是我正在使用的代码片段 import argparse

我正在尝试构建一个支持分析工具,它将允许最终用户使用来自多个来源的数据创建自己的仪表板,其中一个来源是Google analytics。我使用谷歌分析核心报告API获取数据。但是现在,我正在手动插入我的用户帐户的视图来获取数据。因为我是为最终用户构建它的,所以当他们使用oauth授权我的应用程序时,我需要能够以编程方式(使用API)获取用户帐户的视图。我见过像databox这样的工具,它们已经实现了这一点,所以我想知道如何复制相同的功能。下面是我正在使用的代码片段

import argparse

from apiclient.discovery import build
import httplib2
from oauth2client import client
from oauth2client import file
from oauth2client import tools

SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
CLIENT_SECRETS_PATH = 'client_secrets.json' # Path to client_secrets.json file.
VIEW_ID = 'xxxxxx' #manually inserted view I'd here



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

  Returns:
    analytics an authorized analyticsreporting service object.
  """
  # Parse command-line arguments.
  parser = argparse.ArgumentParser(
      formatter_class=argparse.RawDescriptionHelpFormatter,
      parents=[tools.argparser])
  flags = parser.parse_args([])

  # Set up a Flow object to be used if we need to authenticate.
  flow = client.flow_from_clientsecrets(
      CLIENT_SECRETS_PATH, scope=SCOPES,
      message=tools.message_if_missing(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.
  storage = file.Storage('analyticsreporting.dat')
  credentials = storage.get()
  if credentials is None or credentials.invalid:
    credentials = tools.run_flow(flow, storage, flags)
  http = credentials.authorize(http=httplib2.Http())

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

  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': '7daysAgo', 'endDate': 'today'}],
          'metrics': [{'expression': 'ga:sessions'}]
        }]
      }
  ).execute()


def print_response(response):
  """Parses and prints the 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', [])
    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):
        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()

我自己找到了答案。我们必须使用管理API获取特定帐户的所有视图Id,并将其作为参数传递给核心报告API以获取度量/维度