【问题标题】:Access Google Analytics API without generating service account client_secrets在不生成服务帐户 client_secrets 的情况下访问 Google Analytics API
【发布时间】: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


【解决方案1】:

如果您使用service account flow,您需要做的就是要求您的客户向您需要访问的分析帐户/属性/视图添加一个额外的用户(这只是一个 api 帐户连接),然后也意味着您不需要构建 oauth2 流。

这里有关于如何设置它并将其与 python 库一起使用的分步说明:

https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-py

【讨论】:

    猜你喜欢
    • 2013-08-30
    • 2019-01-05
    • 1970-01-01
    • 1970-01-01
    • 2012-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-10
    相关资源
    最近更新 更多