购买Google Analytics(分析)API(V4),我想上传文件“产品数据”
这是GA文档中的示例代码
from apiclient.http import MediaFileUpload
try:
media = MediaFileUpload('custom_data.csv',
mimetype='application/octet-stream',
resumable=False)
daily_upload = analytics.management().uploads().uploadData(
accountId='123456',
webPropertyId='UA-123456-1',
customDataSourceId='9876654321',
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))
这是我要做的,但是关于这部分,我仍然有一个问题-analytics.management().uploads()
import argparse
from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
import httplib2
from oauth2client import client
from oauth2client import file
from oauth2client import tools
from googleapiclient.http import MediaFileUpload
# SET VARS
CUSTOM_DATA_SOURCE_ID='_xxxxxxx'
WEB_PROPERTY_ID='UA-xxxxx-1'
ACCOUNT_ID='xxxxxx'
CSV_IMPORT_FILE_LOCATION='test_file.csv'
CREDENTIALS_KEY_FILE_LOCATION='key.json'
def get_service(api_name, api_version, scope, key_file_location):
credentials = ServiceAccountCredentials.from_json_keyfile_name(
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', 'v4', scope, CREDENTIALS_KEY_FILE_LOCATION)
# Upload CSV Data
uploadCSV(service)
if __name__ == '__main__':
main()
这是我一直收到的错误:
AttributeError: 'Resource' object has no attribute 'management'
有什么建议吗?
我认为这是因为我没有这些方法(management()。uploads()),但这就是文档中的示例。
答案 0 :(得分:0)
当前的分析API v4仅包含API的报告方。要访问管理端点,您必须使用v3。尝试使用API的v3版本重写代码。
要开始更改此行:
service = get_service('analytics', 'v3', scope, CREDENTIALS_KEY_FILE_LOCATION)
但是它可能需要更多的重写。