gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:07:12 24 4
gpt4 key购买 nike

我正在尝试使用其文档提供的代码访问 Google Analytics 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 的情况下访问 Google Analytics API(=获取该 token )?

最佳答案

授权 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 并授予该用户访问您的 Analytics 数据的权限。

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

关于python - 如何从 Python (Django) 中的 Google Analytics 获取最受欢迎的页面列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23303686/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com