Firestore第二代Python云函数触发报错:需1个参数却传入2个
解决Firestore第二代Python云函数参数不匹配的TypeError问题
这个错误是因为触发器配置方式冲突导致的:你同时用了代码里的装饰器和部署命令里的手动触发器参数,两种方式对函数参数的要求不一致,具体解决方法二选一:
方案一:保留装饰器配置,简化部署命令
你的代码已经通过@on_document_created(document="test/{testId}")定义了完整的触发器规则,部署命令里不需要再重复指定触发器相关参数,否则会导致调用时传递的参数数量不匹配。
修改后的部署命令:
gcloud functions deploy example --gen2 --project test-project --runtime python311 --memory 512 --region europe-west3 --env-vars-file prod.yml
方案二:保留部署命令参数,修改函数签名
如果坚持用部署命令指定触发器,需要去掉代码里的@on_document_created装饰器,同时让函数接受两个参数(event和context)——手动配置触发器时,Cloud Functions会默认传递这两个参数给函数。
修改后的代码:
def example(event: Event[DocumentSnapshot], context): print("Hello World") pass
同时修正部署命令里的路径参数(之前的document=''为空,要和你的集合路径对应):
gcloud functions deploy example --gen2 --trigger-event-filters=type=google.cloud.firestore.document.v1.created --trigger-event-filters=database='(default)' --trigger-event-filters-path-pattern=document='test/{testId}' --project test-project --runtime python311 --memory 512 --region europe-west3 --env-vars-file prod.yml
两种方案选其一即可,推荐方案一,因为装饰器方式能让代码和触发器配置绑定,更直观也不容易出错。
内容的提问来源于stack exchange,提问作者Carlo
相关产品推荐
相关产品推荐

