【发布时间】:2017-03-27 21:11:25
【问题描述】:
大家好,我一直在用 Python 编写 Bing Analytics 到 Google 分析脚本。我最近发现我的 goole 分析上传脚本出了什么问题,在修复之后我遇到了一个新问题。我不断收到错误有一个 API 错误:403:禁止。我查看了谷歌发布的所有 403 错误信息,并纠正了我认为错误的所有内容,但仍然出现错误。如果有人可以帮助我解决这个问题,那就太好了。下面是我用于上传脚本的代码。
"""A simple example of how to access the Google Analytics API."""
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
import csv, os, shutil, glob, datetime
from datetime import date, timedelta
from apiclient.http import MediaFileUpload
from apiclient.errors import HttpError
home = os.environ["HOME"]
dt = datetime.datetime.now().strftime("%m_%d_%y")
def get_service(api_name, api_version, scope, key_file_location,
service_account_email):
"""Get a service that communicates to a Google API.
Args:
api_name: The name of the api to connect to.
api_version: The api version to connect to.
scope: A list auth scopes to authorize for the application.
key_file_location: The path to a valid service account p12 key file.
service_account_email: The service account email address.
Returns:
A service that is connected to the specified API.
"""
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 get_first_profile_id(service):
# Use the Analytics service object to get the first profile id.
# Get a list of all Google Analytics accounts for this user
accounts = service.management().accounts().list().execute()
if accounts.get('items'):
# Get the first Google Analytics account.
account = accounts.get('items')[0].get('id')
# Get a list of all the properties for the first account.
properties = service.management().webproperties().list(
accountId=account).execute()
if properties.get('items'):
# Get the first property id.
property = properties.get('items')[0].get('id')
# Get a list of all views (profiles) for the first property.
profiles = service.management().profiles().list(
accountId=account,
webPropertyId=property).execute()
if profiles.get('items'):
# return the first view (profile) id.
return profiles.get('items')[0].get('id')
return None
def get_results(service, profile_id):
# Use the Analytics Service Object to query the Core Reporting API
# for the number of sessions within the past seven days.
return service.data().ga().get(
ids='ga:' + profile_id,
start_date='7daysAgo',
end_date='today',
metrics='ga:sessions').execute()
def print_results(results):
# Print data nicely for the user.
if results:
print 'View (Profile): %s' % results.get('profileInfo').get('profileName')
print 'Total Sessions: %s' % results.get('rows')[0][0]
else:
print 'No results found'
def main():
# Define the auth scopes to request.
scope = ['https://www.googleapis.com/auth/analytics.readonly']
# Use the developer console and replace the values with your
# service account email and relative location of your key file.
service_account_email = 'uploader@bing-ads-analytics.iam.gserviceaccount.com'
key_file_location = home+'/Desktop/Bing-Ads-Analytics-5684236fdf8e.p12'
# Authenticate and construct service.
service = get_service('analytics', 'v3', scope, key_file_location,
service_account_email)
profile = get_first_profile_id(service)
print_results(get_results(service, profile))
try:
media = MediaFileUpload('Bing_Ad_Upload'+dt+'.csv',
mimetype='application/octet-stream',
resumable=False)
daily_upload = service.management().uploads().uploadData(
accountId='XXXXXXXX',
webPropertyId='UA-XXXXXXXX-1',
customDataSourceId='XXXXXXXXXXXXXXXXXXXXXX',
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))
if __name__ == '__main__':
main()
编辑!!!
我发现错误发生在哪里。 daily_upload 有问题。有人可以向我解释一下比 google 给出的在哪里可以找到 accountid、webproprtyid 和 customdatasourceid 更详细的解释吗?谢谢。
【问题讨论】:
-
您的授权是否正确?
-
是的,因为我在脚本中有它要求的 .p12 文件我错过了谷歌分析后端的步骤或其他什么
标签: python python-2.7 google-analytics google-analytics-api