代码之家  ›  专栏  ›  技术社区  ›  Bogdan Lashkov

对Google Analytics示例的误解(上传数据)

  •  1
  • Bogdan Lashkov  · 技术社区  · 8 年前

    我有个问题 this script example . 有一个代码段:

    daily_upload = analytics.management().uploads().uploadData(
      accountId='123456',
      webPropertyId='UA-123456-1',
      customDataSourceId='9876654321',
      media_body=media).execute()
    

    我不知道我可以从哪个模块导入 分析 .management()方法。

    2 回复  |  直到 8 年前
        1
  •  1
  •   Bogdan Lashkov    7 年前
    import sys
    import logging
    from pprint import pprint
    
    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']
    DISCOVERY_URI = 'https://analyticsreporting.googleapis.com/$discovery/rest'
    CLIENT_SECRETS_PATH = 'client_id.json'
    VIEW_ID = ''
    
    
    logger = logging.getLogger(name)
    
    
    def initialize_analyticsreporting():
        flow = client.flow_from_clientsecrets(
            CLIENT_SECRETS_PATH, scope=SCOPES,
            message=tools.message_if_missing(CLIENT_SECRETS_PATH))
    
        storage = file.Storage('analyticsreporting.dat')
        credentials = storage.get()
        if credentials is None or credentials.invalid:
            credentials = tools.run_flow(flow, storage)
        http = credentials.authorize(http=httplib2.Http())
    
        analytics = build(
            'analytics', 'v4',
            http=http, discoveryServiceUrl=DISCOVERY_URI)
    
        return analytics
    
    
    def main():
        analytics = initialize_analyticsreporting()
        data_f = open("report_data.csv", "w")
    
        page_token = "7000"
        request = {
            'reportRequests': [{
                'viewId': VIEW_ID,
                'dateRanges': [{
                    'startDate': '2017-01-01',
                    'endDate': '2018-02-12',
                }],
                'metrics': [{'expression': 'ga:users'}],
                "dimensions": [
                    {"name": "ga:dimension2"},
                    {"name": "ga:dimension3"},
                ],
    
                "pageToken": page_token,
            }]
        }
    
        for n, f in enumerate(request['reportRequests'][0]['dimensions']):
            data_f.write("%s\t" % f["name"])
    
        data_f.write("pageToken\r\n")
    
        while True:
            response = analytics.reports().batchGet(body=request).execute()
    
            rows = response['reports'][0]['data']['rows']
            print("loaded %d rows..." % len(rows))
    
            for row in rows:
                str = ''
                for val in row['dimensions']:
                    str += val + '\t'
    
                data_f.write(str + page_token + '\r\n')
    
            if "nextPageToken" not in response['reports'][0]:
                break
    
            page_token = response['reports'][0]['nextPageToken']
            request['reportRequests'][0]['pageToken'] = page_token
    
        data_f.close()
    
    
    if name == 'main':
        main()
    
        2
  •  0
  •   Tredecies    7 年前

    您需要构建 分析 . 以下是 quickstart :

    from apiclient.discovery import build
    from oauth2client.service_account import ServiceAccountCredentials
    
    
    SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
    KEY_FILE_LOCATION = '<REPLACE_WITH_JSON_FILE>'
    VIEW_ID = '<REPLACE_WITH_VIEW_ID>'
    
    
    def initialize_analyticsreporting():
      """Initializes an Analytics Reporting API V4 service object.
    
      Returns:
        An authorized Analytics Reporting API V4 service object.
      """
      credentials = ServiceAccountCredentials.from_json_keyfile_name(
          KEY_FILE_LOCATION, SCOPES)
    
      # Build the service object.
      analytics = build('analyticsreporting', 'v4', credentials=credentials)
    
      return analytics
    

    您可以使用 初始化\u分析报告 具体如下:

    analytics = initialize_analyticsreporting()
    daily_upload = analytics.management().uploads().uploadData(
      accountId='123456',
      webPropertyId='UA-123456-1',
      customDataSourceId='9876654321',
      media_body=media).execute()