如何从 Google 服务帐户密钥文件中获取访问令牌?

时间:2021-04-19 13:01:05

标签: python google-cloud-platform google-authentication

我正在尝试访问我设置的 automL 模型预测端点,我已经创建了一个服务帐户并向其添加了正确的角色,现在我正在尝试在 Python 中调用该端点,但我不知道如何称之为:这是我尝试过的。密钥文件是从谷歌下载的所以很好。

from google.oauth2 import service_account
project_id = 'aaa'
endpoint_id = 'bbb'
with open('./ServiceAccountKey.json') as source:
    info = json.load(source)
credentials = service_account.Credentials.from_service_account_info(info)
scoped_credentials = credentials.with_scopes(
    ['https://www.googleapis.com/auth/cloud-platform'])
access_token = scoped_credentials.get_access_token()
endpoint = f"https://us-central1-aiplatform.googleapis.com/v1alpha1/projects/{project_id}/locations/us-central1/endpoints/{endpoint_id}:predict"
headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer " + access_token}
payload = {}
x = requests.post(endpoint, data = payload, header=headers)
print(x)

我得到的错误是这样的:

AttributeError: 'Credentials' object has no attribute 'get_access_token'

我已授予服务帐户的权限:

enter image description here

1 个答案:

答案 0 :(得分:1)

最好的方法是使用 AI Platform Python client library。将 GOOGLE_APPLICATION_CREDENTIALS 环境变量设置为您的服务帐户文件的路径,您就可以开始了。

如果有现成的库可用,最好不要自己处理访问令牌和刷新令牌。

相关问题