Python 对谷歌分析示例的误解(上传数据)

Python 对谷歌分析示例的误解(上传数据),python,google-analytics,google-api,Python,Google Analytics,Google Api,我有一个问题。有一段代码片段: daily_upload = analytics.management().uploads().uploadData( accountId='123456', webPropertyId='UA-123456-1', customDataSourceId='9876654321', media_body=media).execute() 我不知道从哪个模块可以导入分析.management()方法。您需要构建分析。以下是来自以下方面的示例: fr

我有一个问题。有一段代码片段:

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

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

您需要构建分析。以下是来自以下方面的示例:

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
analytics = initialize_analyticsreporting()
daily_upload = analytics.management().uploads().uploadData(
  accountId='123456',
  webPropertyId='UA-123456-1',
  customDataSourceId='9876654321',
  media_body=media).execute()
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()