ver*_*4ka 6 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()
Run Code Online (Sandbox Code Playgroud)
但问题是此代码打开浏览器并要求用户允许访问分析服务.有没有人知道如何在没有oauth2的情况下访问Google AnalyticsAPI(=获取该令牌)?
授权 Google API 的方法有多种。您正在使用网络服务器模式,该模式允许您代表您的客户端访问 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)
Run Code Online (Sandbox Code Playgroud)
这将以用户身份访问您的 Google Analytics 帐户SERVICE_ACCOUNT_EMAIL
,因此您必须进入 Google Analytics 并授予该用户访问您的 Analytics 数据的权限。
改编自: https: //developers.google.com/drive/web/service-accounts