首页 > 解决方案 > 烧瓶应用程序未处理错误输入,未在邮递员中显示错误消息

问题描述

我有一个烧瓶应用程序并在 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 个文件”

标签: pythonflask

解决方案


实际上这段代码有两个问题,错误是:
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})

这应该可以解决它,注意这两种情况


推荐阅读