gpt4 book ai didi

python - 在 python 中使用 "allow unauthenticated"的谷歌云部署函数

转载 作者:行者123 更新时间:2023-12-04 01:29:41 26 4
gpt4 key购买 nike

我正在使用 Python 从另一个 Cloud Function 部署一个 Google Cloud Function。请参阅下面的代码:

import requests
import json


def make_func(request):


# Get the access token from the metadata server
metadata_server_token_url = 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token?scopes=https://www.googleapis.com/auth/cloud-platform'
token_request_headers = {'Metadata-Flavor': 'Google'}
token_response = requests.get(metadata_server_token_url, headers=token_request_headers)
token_response_decoded = token_response.content.decode("utf-8")
jwt = json.loads(token_response_decoded)['access_token']

# Use the api to create the function
response = requests.post('https://cloudfunctions.googleapis.com/v1/projects/myproject/locations/us-central1/functions',
json={"name":"projects/my-project/locations/us-central1/functions/funct","runtime":"python37","sourceArchiveUrl":"gs://bucket/main.zip","entryPoint":"hello_world","httpsTrigger": {} },
headers={'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer {}'.format(jwt)} )
if response:
return 'Success! Function Created'
else:
return str(response.json())

但是这个函数并没有自动开启“allow unauthenticated”。因此,不允许来自外部的请求。在部署新功能时,如何更改我的 Python 代码以添加此功能?

谢谢

最佳答案

您还需要为 allUsers 成员授予 Cloud Functions Invoker 角色:

from googleapiclient.discovery import build
service = build('cloudfunctions', 'v1')

project_id = ...
location_id = ...
function_id = ...
resource = f'projects/{project_id}/locations/{location_id}/functions/{function_id}'

set_iam_policy_request_body = {
'policy': {
"bindings": [
{
"role": "roles/cloudfunctions.invoker",
"members": ["allUsers"],
},
],
},
}

request = service.projects().locations().functions().setIamPolicy(
resource=resource,
body=set_iam_policy_request_body,
)
response = request.execute()

print(response)

这使用了 google-api-python-client包。

关于python - 在 python 中使用 "allow unauthenticated"的谷歌云部署函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61277107/

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