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

How to get Access Token from Google Service Account key file?

我正在尝试访问我设置的 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'

我授予服务帐户的权限:

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

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