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

6 投票
2 回答
1320 浏览
提问于 2025-04-18 04:18

我正在尝试使用谷歌提供的文档中的代码来访问谷歌分析API: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的情况下访问谷歌分析API(也就是获取那个令牌)?

2 个回答

1

因此,我写了一篇博客文章,里面分享了一个对我有效的解决方案:

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
4

有几种方法可以授权使用Google的API。你现在使用的是Web Server模式,这种模式允许你代表客户访问Google服务,但在这种情况下,你其实应该使用服务账户

首先,确保你的云项目在Google Cloud Console中启用了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中给这个用户访问你的分析数据的权限。

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

撰写回答