我有一个flask应用程序,并在python中对其进行了测试。我发送2个文件,如果没有给出-它应该给我json错误msg“需要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个文件”
答案 0 :(得分:1)
实际上此代码中有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})
这应该解决它,注意2例