【问题标题】:How to get Access Token from Google Service Account key file?如何从 Google 服务帐户密钥文件中获取访问令牌?
【发布时间】:2021-04-19 13:01:05
【问题描述】:

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

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'

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

【问题讨论】:

  • 1) access_token = scoped_credentials.token。 2) 您可能需要先致电scoped_credentials.refresh()。 2) 提示:使用from_service_account_file() 而不是from_service_account_info()。 3)您可以在单个调用而不是多个调用中添加范围。 credentials = service_account.Credentials.from_service_account_file('ServiceAccountKey.json', scopes=['https://www.googleapis.com/auth/cloud-platform'])

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


【解决方案1】:

最好的方法是使用AI Platform Python client library。将GOOGLE_APPLICATION_CREDENTIALS 环境变量设置为您的服务帐户文件的路径,一切顺利。

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

【讨论】:

    猜你喜欢
    • 2015-04-29
    • 2017-10-07
    • 2016-04-29
    • 1970-01-01
    • 2015-02-11
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    • 1970-01-01
    相关资源
    最近更新 更多