python - 烧瓶应用程序未处理错误输入,未在邮递员中显示错误消息
问题描述
我有一个烧瓶应用程序并在 python 中对其进行测试。我发送 2 个文件,如果没有给出 - 它应该给我 json 错误消息“需要 2 个文件”
@app.route('/compare_voices', methods = ['POST'])
def compare_voices():
if request.method == 'POST':
file1 = request.files["file1"]
file2 = request.files["file2"]
if file1 == None or file2 == None:
return jsonify({'response':"need 2 files!"}) #this should trigger
else:
answer = 'ok'
return jsonify({'response': answer})
相反,它像这样崩溃:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'file1' // Werkzeug Debugger</title>
但我希望处理这种情况,只看到错误消息“需要 2 个文件”
解决方案
实际上这段代码有两个问题,错误是:
1.其中一个参数文件不存在
2.其中一个文件是空的(参数存在,但没有选择文件,实际上应该在前端处理)
@app.route('/comp', methods = ['POST'])
def compare_voices():
if request.method == 'POST':
try:
file1 = request.files["file1"]
file2 = request.files["file2"]
except:
return jsonify({'response':"need 2 files!"})
if file1.filename == '' or file2.filename == '':
answer = "need 2 files!"
else:
answer = 'ok'
return jsonify({'response': answer})
这应该可以解决它,注意这两种情况
推荐阅读
- javascript - 如何在 Css 和 JavaScript 中创建折纸效果?
- python - 拥抱脸管道的多处理:执行没有结束
- sql - 如何使用 drop_duplicates 将 pandas 重写为 sql
- mysql - 基于类别的价值总和
- node.js - mongodb在数组中查找
- asp.net-core - 如何以对开发人员友好的方式测试针对 .NET 5.0 服务器运行的 .NET 4.8 客户端?
- python - RuntimeError:预期一维目标张量,不支持多目标 Pytorch
- firebase - FirebaseError:Firebase:未创建 Firebase 应用“[DEFAULT]”
- c - 取消初始化 FatFS 并安装另一张 SD 卡
- kubernetes - 如何将 kubectl 规模部署设置为部署文件?