从触发事件选项测试Python 3.7 Google Cloud Function的报错问题咨询
GCP HTTP类Cloud Function测试缺参报错解决
报错核心原因
- HTTP触发的Python版Cloud Function遵循固定运行时入参规则:入口函数仅会接收到1个代表HTTP请求的
request对象,不会自动将业务参数作为位置形参注入函数。你当前定义的upload_blob(bucket_name, blob_text, destination_blob_name)签名,运行时无法自动为三个形参赋值,因此触发缺参报错。 - 原有代码存在遗留错误:print语句中引用了未定义的
source_file_name变量,就算参数匹配成功,也会触发名称不存在的运行时故障。
代码改造方案
按照HTTP触发的函数规范调整入口逻辑,从请求中解析所需业务参数,可运行代码参考:
from google.cloud import storage import flask def upload_blob(request): request_params = request.get_json() bucket_name = request_params.get("bucket_name") blob_text = request_params.get("blob_text") destination_blob_name = request_params.get("destination_blob_name") if not all([bucket_name, blob_text, destination_blob_name]): return flask.jsonify({"error": "缺少必填请求参数"}), 400 storage_client = storage.Client() bucket = storage_client.get_bucket(bucket_name) blob = bucket.blob(destination_blob_name) blob.upload_from_string(blob_text) print(f"对象 {destination_blob_name} 已上传至存储桶 {bucket_name}") return flask.jsonify({ "status": "success", "uploaded_uri": f"gs://{bucket_name}/{destination_blob_name}" }), 200
测试页正确输入格式
你之前尝试的{"name":[param1,param2,param3]}格式无法匹配代码的参数解析逻辑,会直接导致参数注入失败。在Cloud Function详情页「测试」标签页,按照代码解析的参数键填写JSON请求体即可,参考格式:
{ "bucket_name": "你的GCS存储桶名称", "blob_text": "要上传的文本内容", "destination_blob_name": "test/demo.txt" }
内容的提问来源于stack exchange,提问作者Prany
相关产品推荐
相关产品推荐

