使用Python 2.7.x连接到Google Analytics时出现403错误

时间:2014-12-28 07:08:58

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

我尝试使用Python客户端(google-api-python-client)从Google AnalyticsAPI获取数据。这是我使用的代码:

from apiclient import discovery
from oauth2client.client import SignedJwtAssertionCredentials
from httplib2 import Http

with open("ManagementGate-622edd43c0dd.p12") as f:
    private_key = f.read()

credentials = SignedJwtAssertionCredentials(
    'XXXXXXXX@developer.gserviceaccount.com',
    private_key,
    'https://www.googleapis.com/auth/analytics.readonly')

http_auth = credentials.authorize(Http())

service = discovery.build('analytics', 'v3', http=http_auth)

result = service.data().ga().get(
      ids='ga:79873569',
      start_date='7daysAgo',
      end_date='today',
      metrics='ga:visits,ga:sessions,ga:pageviews').execute()

我在凭据页面上创建了一个服务帐户。但是,我收到如下错误:

googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/analytics/v3/data/ga?metrics=ga%3Avisits%2Cga%3Asessions%2Cga%3Apageviews&alt=json&end-date=today&ids=ga%3A79873569&start-date=7daysAgo returned "User does not have any Google Analytics account.">

我所遵循的说明来自:https://developers.google.com/accounts/docs/OAuth2ServiceAccount 还有什么我需要做的吗?为什么我会收到此错误?我已在API页面上启用了Analytics API。

1 个答案:

答案 0 :(得分:8)

您正尝试使用服务帐户访问Google AnalyticsAPI。默认情况下,服务帐户无权访问任何Google Analytics帐户。

您需要做的是从Google Developer控制台获取服务帐户电子邮件地址。转到Google Analytics网站的“管理”部分。通过 ACCOUNT 级别授予此服务帐户访问权限,您必须将 ACCOUNT 级别设置为您要访问的Google Analytics帐户。

它不适用于网络媒体资源或视图级别,必须是帐户级别。