Google Cloud Function测试正常但部署后调用失败求助
问题解答
1. 浏览器地址栏用?url=...调用是否错误?
完全没问题。这种方式是通过URL查询参数传递参数,属于HTTP GET请求的标准用法,错误根源是代码逻辑bug:在处理查询参数的elif分支里,错误使用了request_json['url'],而GET请求不会携带JSON请求体,request_json会是None,从而触发TypeError。
2. 如何实现与测试界面相同的调用效果?
测试界面是通过POST请求+JSON请求体传递参数(比如{"url": "https://xxx"}),要实现相同效果有两种方式:
- 方式一:保持代码对JSON请求体的支持,用POST请求发送JSON数据(下文有具体调用示例)
- 方式二:修正代码
elif分支的bug,让GET请求的查询参数正常工作,修正后的核心代码片段如下:
elif request_args and 'url' in request_args: url = request_args['url'] # 将request_json改为request_args response = requests.get(url) with open('image.jpg', 'wb') as imagem: imagem.write(response.content) tf_classifier = Model(model_file, label_file) results = tf_classifier.classify('image.jpg', min_confidence=0.01) string = "According to the model, your image corresponds to, in descending order of confidence:\n" for r in results: string += f"\t {r['label']}, with a confidence of {r['confidence']};\n"
3. curl或Python requests库的正确调用方式
方式一:模拟测试界面的POST请求(JSON体)
curl命令
curl -X POST "https://myprojectandfunction.net/function-1" \ -H "Content-Type: application/json" \ -d '{"url": "https://xxx"}'
Python requests代码
import requests func_url = "https://myprojectandfunction.net/function-1" payload = {"url": "https://xxx"} headers = {"Content-Type": "application/json"} response = requests.post(func_url, json=payload) print(response.text)
方式二:GET请求(URL查询参数,需先修正代码bug)
curl命令
curl "https://myprojectandfunction.net/function-1?url=https://xxx"
Python requests代码
import requests func_url = "https://myprojectandfunction.net/function-1" params = {"url": "https://xxx"} response = requests.get(func_url, params=params) print(response.text)
额外优化建议
- 每次请求都重新下载模型和标签会降低性能,建议把模型初始化逻辑移到函数外部(Cloud Function冷启动时加载一次,后续请求复用)
- 临时文件
image.jpg建议使用tempfile模块,避免多请求时的文件冲突 - 增加异常处理逻辑,比如图片URL无法访问、图片格式错误等情况,避免函数直接崩溃
内容的提问来源于stack exchange,提问作者Filipe Gomes
相关产品推荐
相关产品推荐

