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

时间:2018-03-06 15:17:37

标签: python google-analytics google-api

我遇到this script example的问题。有一段代码:

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

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

2 个答案:

答案 0 :(得分:1)

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()

答案 1 :(得分:0)

您需要构建分析。这是来自quickstart的示例:

User.current

您可以按以下方式使用 initialize_analytics报告中的返回值:

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