从 google.oauth2.Credentials 获取访问令牌

Get access token from google.oauth2.Credentials

目前,我正在为我的 TF2 模型构建异步前端。现在它作为两个服务工作,第一个服务是一个扭曲的服务,第二个服务是一个 TensorFlow 服务。

正在使用异步 Web 客户端异步查询模型。出于实际原因,我已经将该模型部署到 GCP AI 平台中,我可以使用示例中的 python 代码从中获取数据,这没问题。

但问题是 Google API 客户端是同步的,我想使用异步客户端。因为据我所知,GCP 没有积极支持的异步客户端,所以我试图直截了当并使用 REST。 TensorFlow serving 上的模型输入是相同的(我相信 GCP AI Platform 在内部使用 TensorFlow serving)。

要执行异步调用,我需要:

  1. 型号URL。 (我有)
  2. 输入数据。 (我也有)
  3. 访问令牌。

我看到了一些例子:

import googleapiclient.discovery
credentials = service_account.Credentials.from_service_account_file(
    '/path/to/key.json',
    scopes=['https://www.googleapis.com/auth/cloud-platform'])

但问题是 credential.tokenNone,所以我不能使用它。

所以我有一个问题:我怎样才能获得访问令牌以用于其余请求?

或者也许还有另一种更好的方法?

我已经看到以下问题: 但我认为这有点无关紧要。

只关注“我如何获得访问令牌?”,您将需要:

  1. 创建服务帐户
  2. 使用 Google 授权库
  3. 运行代码

NOTE If you're running the code off-GCP (i.e. not on App Engine, Compute Engine, GKE etc.), then you will need to create a Key for the Service Account and you will need to export GOOGLE_APPLICATION_CREDENTIALS=path/to/your/key.json. Application Default Credentials (see below) simplify auth.

参见:Authenticating as a Service Account

并且:

import google.auth

from googleapiclient.discovery import build

SCOPES = ["https://www.googleapis.com/auth/cloud-platform"]

creds, project_id = google.auth.default(scopes=SCOPES)

service = build(GOOGLE_API, GOOGLE_API_VERSION, credentials=creds)

以下代码设置用于管理来自服务帐户的凭据(OAuth 令牌)的数据结构。此时没有请求令牌。

credentials = service_account.Credentials.from_service_account_file(
    '/path/to/key.json',
    scopes=['https://www.googleapis.com/auth/cloud-platform'])

在需要之前,不会从 Google 身份验证服务器请求令牌。有几个原因: a) 网络调用需要时间——网络故障需要大量时间; b) 令牌过期; c) 令牌被缓存直到它们(几乎)过期。

要生成令牌,请调用 refresh() 方法:

import google.auth.transport.requests
request = google.auth.transport.requests.Request()
credentials.refresh(request)

credential.token 现在将包含一个 OAuth 访问令牌,否则将抛出异常(网络错误等)。