python - 谷歌云部署功能在python中“允许未经身份验证”
问题描述
我正在使用 Python 从另一个云函数部署一个谷歌云函数。请参阅下面的代码:
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())
但是,此功能不会自动启用“允许未经身份验证”。因此,不允许来自外部的请求。在部署新功能时,如何更改我的 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)
推荐阅读
- reactjs - 如何在具有多个 CRA 的 monorepo 中重用“公共”文件夹?
- python - Python没有从列表中打印
- wordpress - Wordpress 表单链接断开
- java - 如何将线性布局中的项目显示为两列
- css - font-face 适用于桌面 Chrome 和桌面 Firefox,但不适用于桌面 Safari 或 iOS 浏览器
- javascript - 使用 getElementsByClassName() 获取特定类的问题(具有相似名称的多个类)
- c# - ML.NET 和多对多关系
- javascript - 需要在 Javascript 中评估下拉列表中的内容
- javascript - Google Maps API v3:允许自定义 OverlayView 上的默认上下文菜单
- scikit-learn - sklearn 线性回归管道可以在输出变量上设置最大上限吗?