我正在使用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))
答案 0 :(得分:2)
您使用的脚本假定您已经过身份验证并创建了服务。在运行此脚本之前,需要构建服务对象。见这个例子:
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()
答案 1 :(得分:1)
错误在于说明发生了什么:您之前没有定义第9行中使用的名称analytics
daily_upload = analytics.management().uploads().uploadData(
您需要完成第一步才能使用并导入它。您还需要一个帐户,因为它需要身份验证。
https://developers.google.com/analytics/devguides/reporting/core/v3/quickstart/service-py
设置完成后,您应该阅读
https://developers.google.com/analytics/devguides/reporting/core/v3/coreDevguide
你应该没事!