如何通过gcloud部署响应多个GCS事件的Cloud Functions Gen2?
解决Cloud Functions Gen2监听多个GCS事件的问题
Cloud Functions Gen2(基于Eventarc)不支持用通配符(如google.storage.object.*)匹配事件类型,也不能在单个--trigger-event参数里用逗号分隔多个事件。要同时监听finalize和delete事件,你需要为每个事件类型添加单独的--trigger-event参数,同时共享bucket的过滤条件。
正确的部署命令
gcloud functions deploy myfunc \ --region europe-north1 \ --project "myproj" \ --gen2 \ --runtime python311 \ --trigger-event "google.storage.object.finalize" \ --trigger-event "google.storage.object.delete" \ --trigger-event-filters="bucket=mybucket" \ --source "mydir" \ --entry-point "myfunc" \ --timeout 100s
函数内区分事件类型
部署完成后,你的Python函数可以通过事件对象的type字段判断当前触发的事件类型,示例代码如下:
def myfunc(event, context): event_type = event["type"] if event_type == "google.storage.object.finalize": # 处理对象上传完成逻辑 print("对象已上传完成") elif event_type == "google.storage.object.delete": # 处理对象删除逻辑 print("对象已被删除") # 其他逻辑...
内容的提问来源于stack exchange,提问作者Sagi Mann
相关产品推荐
相关产品推荐

