gpt4 book ai didi

python - 使用服务帐户从 python 调用 Google Cloud Function 进行身份验证

转载 作者:行者123 更新时间:2023-12-03 20:25:57 25 4
gpt4 key购买 nike

我有一个触发器类型设置为 HTTP 的云函数,还有一个有权调用云函数的服务帐户。我想从 python 脚本调用云函数。我正在使用以下脚本来调用该函数:

from google.oauth2 import service_account
from google.auth.transport.urllib3 import AuthorizedHttp

credentials = service_account.Credentials.from_service_account_file('/path/to/service-account-credentials.json')

scoped_credentials = credentials.with_scopes(['https://www.googleapis.com/auth/cloud-platform'])

authed_http = AuthorizedHttp(scoped_credentials)

response = authed_http.request('GET', 'https://test-123456.cloudfunctions.net/my-cloud-function')

print(response.status)

我收到 Unauthorized (401) 错误作为响应。这是正确的调用方式吗?

最佳答案

为了能够调用您的云函数,您需要一个针对云函数端点的 ID token

from google.oauth2 import service_account
from google.auth.transport.requests import AuthorizedSession


url = 'https://test-123456.cloudfunctions.net/my-cloud-function'

creds = service_account.IDTokenCredentials.from_service_account_file(
'/path/to/service-account-credentials.json', target_audience=url)

authed_session = AuthorizedSession(creds)

# make authenticated request and print the response, status_code
resp = authed_session.get(url)
print(resp.status_code)
print(resp.text)

关于python - 使用服务帐户从 python 调用 Google Cloud Function 进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61114822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com