如何从Python(Django)中获取Google Analytics中最受欢迎的网页列表?

时间:2014-04-25 21:54:43

标签: python django google-analytics google-analytics-api

我尝试使用其文档提供的代码访问Google AnalyticsAPI:https://developers.google.com/analytics/solutions/articles/hello-analytics-api

import httplib2
import os

from apiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import run


CLIENT_SECRETS = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'client_secrets.json')
MISSING_CLIENT_SECRETS_MESSAGE = '%s is missing' % CLIENT_SECRETS
FLOW = flow_from_clientsecrets('%s' % CLIENT_SECRETS,
    scope='https://www.googleapis.com/auth/analytics.readonly',
    message=MISSING_CLIENT_SECRETS_MESSAGE,
)
TOKEN_FILE_NAME = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'analytics.dat')


def prepare_credentials():
    storage = Storage(TOKEN_FILE_NAME)
    credentials = storage.get()

    if credentials is None or credentials.invalid:
        credentials = run(FLOW, storage)

    return credentials


def initialize_service():
    http = httplib2.Http()
    credentials = prepare_credentials()
    http = credentials.authorize(http)

    return build('analytics', 'v3', http=http)


def get_analytics():
   initialize_service()

但问题是此代码会打开浏览器并要求用户允许访问分析服务。有没有人知道如何在没有oauth2的情况下访问Google AnalyticsAPI(=获取该令牌?)

2 个答案:

答案 0 :(得分:3)

有几种方法可以授权Google API。您使用的是Web Server模式,可以代表您的客户访问Google服务,但在这种情况下您真正想要使用的是Service Accounts

首先要确保在Google Cloud Console

中为您的Cloud Project启用了Analytics API服务

然后进入Google Cloud Console并创建一个新的服务帐户客户端ID。这将为您提供证书文件和服务帐户电子邮件。这就是你所需要的一切。

以下是如何验证和实例化Analytics API的示例。

import httplib2

from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials

# Email of the Service Account.
SERVICE_ACCOUNT_EMAIL = '<some-id>@developer.gserviceaccount.com'

# Path to the Service Account's Private Key file.
SERVICE_ACCOUNT_PKCS12_FILE_PATH = '/path/to/<public_key_fingerprint>-privatekey.p12'

def createAnalyticsService():
  f = file(SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'rb')
  key = f.read()
  f.close()

  credentials = SignedJwtAssertionCredentials(SERVICE_ACCOUNT_EMAIL, key,
      scope='https://www.googleapis.com/auth/analytics.readonly')
  http = httplib2.Http()
  http = credentials.authorize(http)

  return build('analytics', 'v3', http=http)

这将以SERVICE_ACCOUNT_EMAIL用户身份访问您的Google Analytics帐户,因此您必须访问Google Analytics并授予此用户访问Google Analytics数据的权限。

改编自:https://developers.google.com/drive/web/service-accounts

答案 1 :(得分:1)

结果我写了blog post的解决方案,对我有用:

import httplib2
import os
import datetime

from django.conf import settings

from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials

# Email of the Service Account.
SERVICE_ACCOUNT_EMAIL ='12345@developer.gserviceaccount.com'

# Path to the Service Account's Private Key file.
SERVICE_ACCOUNT_PKCS12_FILE_PATH = os.path.join(
    settings.BASE_DIR,
    '53aa9f98bb0f8535c34e5cf59cee0f32de500c82-privatekey.p12',
)


def get_analytics():
    f = file(SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'rb')
    key = f.read()
    f.close()

    credentials = SignedJwtAssertionCredentials(
        SERVICE_ACCOUNT_EMAIL,
        key,
        scope='https://www.googleapis.com/auth/analytics.readonly',
    )
    http = httplib2.Http()
    http = credentials.authorize(http)

    service = build('analytics', 'v3', http=http)

    end_date = datetime.date.today()
    # 30 days ago
    start_date = end_date - datetime.timedelta(days=30)

    data_query = service.data().ga().get(**{
        'ids': 'ga:123456',  # the code of our project in Google Analytics
        'dimensions': 'ga:pageTitle,ga:pagePath',
        'metrics': 'ga:pageviews,ga:uniquePageviews',
        'start_date': start_date.strftime('%Y-%m-%d'),
        'end_date': end_date.strftime('%Y-%m-%d'),
        'sort': '-ga:pageviews',
    })
    analytics_data = data_query.execute()
    return analytics_data