You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask提交空表单或未选单选按钮时报Bad Request错误如何解决?

问题根因

Flask 中直接使用request.form["键名"]读取表单参数时,如果提交的表单里没有对应参数,会直接触发 400 Bad Request 异常,不会执行后续的错误判断逻辑。你遇到的两种场景都没有选中单选按钮,POST 请求里没有携带ID参数,直接在option = request.form["ID"]这一步就触发了错误,根本走不到你写的返回 error.html 的分支。

修复步骤

  1. 把表单参数读取方式改为request.form.get("键名"),该方法在参数不存在时会返回 None,不会抛出异常
  2. 在 POST 逻辑最开头先校验必填参数是否存在,不存在直接返回错误页
  3. 修正 debug 模式的配置顺序,原有代码中app.debug = True写在app.run()之后,不会生效,需要调换顺序

修改后的核心代码

@app.route("/", methods=['GET', 'POST'])
def index():
    if request.method == "GET":
        return render_template("index.html")

    elif request.method == "POST":
        # 改用get方法取值,参数不存在返回None
        option = request.form.get("ID")
        user_input = request.form.get("id_value", "")
        # 先校验必填参数,覆盖未选单选、未填文本框的场景
        if not option or not user_input:
            return render_template("error.html")
        
        dic, courses = read_csv()
        if option == "student_id":
            if user_input in dic:
                student_id_dic = dic[user_input]
                total_marks = sum(student_id_dic.values())
                return render_template("student_details.html", course_id_data=student_id_dic,
                                       student_id_data=user_input,
                                       total_marks_data=total_marks)
            else:
                return render_template("error.html")

        elif option == "course_id":
            if user_input in courses:
                ct = 0
                max_marks = -1
                total = 0
                mark_list = []
                for student_id in dic:
                    for key, value in dic[student_id].items():
                        if key == user_input:
                            mark_list.append(value)
                            ct = ct + 1
                            total = total + value
                            if value > max_marks:
                                max_marks = value
                plot_hist(mark_list)
                return render_template("course_details.html", average_marks=(total / ct), maximum_marks=max_marks,
                                       img='./static/hist.png')
            else:
                return render_template("error.html")

        return render_template("error.html")
    return render_template("error.html")

if __name__ == "__main__":
    # 把debug设置放到run前面才会生效
    app.debug = True
    app.run(host='0.0.0.0')

内容的提问来源于stack exchange,提问作者user3608646

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 16:24:05