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

Flask表单无法正常运行,持续出现Bad Request错误求助

Flask表单Bad Request错误排查与修复

问题根源

你的视图函数index没有区分GET和POST请求:

  • 当用户首次访问页面(GET请求)时,request.form是空的,此时直接执行request.form["recipe"]会触发KeyError,Flask自动返回400 Bad Request错误。
  • 表单提交后也没有将获取到的数据传递给模板,无法反馈提交结果。

修复后的代码

main.py

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route("/", methods=["GET", "POST"])
def index():
    recipe_name = ""
    if request.method == "POST":
        # 用get方法安全获取表单字段,不存在时返回空字符串
        recipe_name = request.form.get("recipe", "")
    # 将数据传递给模板
    return render_template("index.html", recipe=recipe_name)

if __name__=='__main__': 
    app.run(debug=True)  # 开启调试模式,方便开发时查看详细错误

index.html(可选优化,增加提交结果展示)

{% extends "base.html" %}
{% block content %}
    <h1>Cooking By Myself</h1>
    <!-- 显示提交的食谱名称 -->
    {% if recipe %}
        <p>你提交的食谱:<strong>{{ recipe }}</strong></p>
    {% endif %}
    <form action="/" method="POST">
        <h3>Add Recipe</h3>
        <p>
            <label for="recipe">Name:</label>
            <input type="text" name="recipe" id="recipe"/>
        </p>
        <p><input type="submit" name="submit_recipe"/></p>
    </form>
{% endblock %}

base.html(无需修改)

<!DOCTYPE html>
<html>
  <body>
    {% block content %}
    {% endblock %}
  </body>
</html>

关键修改说明

  1. 区分请求方法:仅在POST请求时处理表单数据,GET请求直接渲染空表单。
  2. 安全获取表单字段:使用request.form.get()替代直接索引,避免因字段缺失引发的错误。
  3. 传递数据到模板:把获取到的食谱名传给模板,实现提交结果的展示。
  4. 开启调试模式:开发阶段开启debug=True,能看到详细的错误堆栈信息,便于快速排查问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 04:57:04