gpt4 book ai didi

python - 找出应该在哪里定义分析

转载 作者:太空宇宙 更新时间:2023-11-03 10:56:34 24 4
gpt4 key购买 nike

我在 python 中使用 Google Analytics api 并不断收到错误

NameError: name 'analytics' is not defined. 

几天来,我一直在 analytics api 站点和 StackOverflow 上寻找答案。如果有人可以指出正确文档的方向或在这里帮助我,将不胜感激。附件是我到目前为止的代码。

from apiclient.http import MediaFileUpload
from apiclient.errors import HttpError

try:
media = MediaFileUpload('Bing_Ad_Test.csv',
mimetype='application/octet-stream',
resumable=False)
daily_upload = analytics.management().uploads().uploadData(
accountId='',
webPropertyId='',
customDataSourceId='',
media_body=media).execute()

except TypeError, error:
# Handle errors in constructing a query.
print 'There was an error in constructing your query : %s' % error

except HttpError, error:
# Handle API errors.
print ('There was an API error : %s : %s' %
(error.resp.status, error.resp.reason))

最佳答案

您正在使用的脚本假定您已经通过身份验证并创建了服务。在运行此脚本之前,您需要构建服务对象。看这个例子:

import argparse

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

import httplib2
from oauth2client import client
from oauth2client import file
from oauth2client import tools
from apiclient.http import MediaFileUpload

# SET VARS
SERVICE_ACCOUNT_EMAIL='XXX'
CUSTOM_DATA_SOURCE_ID='XXX'
WEB_PROPERTY_ID='XXX'
ACCOUNT_ID='XXX'
CSV_IMPORT_FILE_LOCATION='XXX'
CREDENTIALS_KEY_FILE_LOCATION='XXX'

def get_service(api_name, api_version, scope, key_file_location,
service_account_email):

credentials = ServiceAccountCredentials.from_p12_keyfile(
service_account_email, key_file_location, scopes=scope)

http = credentials.authorize(httplib2.Http())

# Build the service object.
service = build(api_name, api_version, http=http)

return service

def uploadCSV(service):
try:
media = MediaFileUpload(CSV_IMPORT_FILE_LOCATION,
mimetype='application/octet-stream',
resumable=False)
daily_upload = service.management().uploads().uploadData(
accountId=ACCOUNT_ID,
webPropertyId=WEB_PROPERTY_ID,
customDataSourceId=CUSTOM_DATA_SOURCE_ID,
media_body=media).execute()

except TypeError, error:
# Handle errors in constructing a query.
print 'There was an error in constructing your query : %s' % error


def main():
# Define the auth scopes to request.
scope = ['https://www.googleapis.com/auth/analytics.edit','https://www.googleapis.com/auth/analytics']

# Authenticate and construct service.
service = get_service('analytics', 'v3', scope, CREDENTIALS_KEY_FILE_LOCATION,
SERVICE_ACCOUNT_EMAIL)

# Upload CSV Data
uploadCSV(service)


if __name__ == '__main__':
main()

关于python - 找出应该在哪里定义分析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40022757/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com