繁体   English   中英

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

[英]How to get a list of most popular pages from Google Analytics in Python (Django)?

我正在尝试使用其文档提供的代码访问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(=获取该令牌)?

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

首先要确保在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

结果我写了一篇博文,里面有一个对我有用的解决方案:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM