【发布时间】:2020-04-05 02:11:50
【问题描述】:
我正在尝试访问客户的 Google Analytics(分析)报告 (v4),因此无法生成自己的 client_secrets.json 文件。过去,我使用 oauth2client 库创建流和存储对象以通过 http 进行身份验证。当前的 google 文档仍然使用 oauth2client 库,根据 pypi.org(和 google),该库已于 2018 年 9 月弃用。
这是我们用于构建服务的当前代码:
import argparse
from apiclient.discovery import build
import httplib2
from oauth2client import client
from oauth2client import file
from oauth2client import tools
def get_service(api_name, api_version, scope, client_secrets_path):
"""Get a service that communicates to a Google API.
Args:
api_name: string The name of the api to connect to.
api_version: string The api version to connect to.
scope: A list of strings representing the auth scopes to authorize for the
connection.
client_secrets_path: string A path to a valid client secrets file.
Returns:
A service that is connected to the specified API.
"""
# Parse command-line arguments.
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
parents=[tools.argparser])
flags = parser.parse_args([])
# Set up a Flow object to be used if we need to authenticate.
flow = client.flow_from_clientsecrets(
client_secrets_path, scope=scope,
message=tools.message_if_missing(client_secrets_path))
# Prepare credentials, and authorize HTTP object with them.
# If the credentials don't exist or are invalid run through the native client
# flow. The Storage object will ensure that if successful the good
# credentials will get written back to a file.
storage = file.Storage(api_name + '.dat')
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = tools.run_flow(flow, storage, flags)
http = credentials.authorize(http=httplib2.Http())
# Build the service object.
service = build(api_name, api_version, http=http)
return service
当前的谷歌文档可以在这里找到: https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/installed-py
如何在不从客户端接收特定 client_secrets 且不使用 oauth2client 的情况下创建此构建?
【问题讨论】:
-
您能说明一下您要达到的目标吗?访问 Analytics Reporting API 需要授权,因此无论您使用什么库,在任何情况下都需要服务帐户或 OAuth 凭据才能发出请求。
标签: python google-cloud-platform google-analytics google-oauth