python - 禁止使用Google Analytics(分析)API 403出错

标签 python python-2.7 google-analytics google-analytics-api

您好,我一直在使用python开发Bing Analytics to Google Analytics脚本。最近,我发现goole分析上传脚本出了什么问题,修复后又遇到了新问题。我不断收到错误,发生API错误:403:禁止。我查看了Google发布的所有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出了点问题。有谁能比谷歌给我更详细的解释给我,比谷歌在哪里可以找到accountid,webproprtyid和customdatasourceid更好,谢谢。

最佳答案

您在以下位置获得了accountId:

# Get the first Google Analytics account.
account = accounts.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()

关于python - 禁止使用Google Analytics(分析)API 403出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41270059/

相关文章:

python - 为什么类在未启动时会得到 "called"? - Python

python - 在 python 中创建 makefile

https - Google 如何将引用从 HTTPS 传递到 HTTP?

api - Analytics API 每个国家/地区的唯一访客

python - 如何在我的页面之间共享导航栏?应用引擎 python Jinja2

python,tkinter,在远程服务器上保存 csv 文件 - 没有 $DISPLAY 环境变量

python - scikit-learn:随机森林 class_weight 和 sample_weight 参数

python - 有没有办法简化这个 if-elif-else 链? ( python 初学者)

python - 使用 pyinstaller 生成的 .exe 在其他 PC 上崩溃 - 如何创建真正没有依赖项的 .exe?

javascript - 如何配置 Google Analytics 以将 URL 参数作为单独的页面进行跟踪