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

Flask使用Bootstrap开关过滤列表触发BadRequestKeyError 400错误问题

问题根因

HTML的checkbox元素默认只有处于勾选状态时,才会将对应name和value提交到后端,未勾选状态下该字段不会出现在POST的form数据中。你切换开关到关闭状态时,提交的POST请求里没有switch字段,直接用request.form['switch']访问不存在的key就会触发BadRequestKeyError。

修复方法

1. 后端代码修改

把request.form['switch']改用get()方法取值,设置默认值规避key不存在的报错,修改后代码如下:

@app.route('/', methods=['POST', 'GET'])
def index():
    conn = get_db_connection()

    if request.method == 'POST':
        # 用get方法取值,字段不存在时默认返回'0'
        switchvalue = request.form.get('switch', '0')
        flash(switchvalue)

        if switchvalue == '1':
            # 注意SQL字符串要用单引号,不要用转义后的"
            rows = conn.execute('SELECT Name, CAST (Points AS int) as Points, isActive FROM table WHERE isActive = \'Active\'').fetchall()
            conn.close()
            return render_template('index.html', rows=rows, switchcheck=1)

    rows = conn.execute('SELECT Name, CAST (Points AS int) as Points, isActive FROM table').fetchall()
    conn.close()
    return render_template('index.html', rows=rows, switchcheck=0)

2. 前端代码优化(可选)

可以把双分支的input简化为单分支,只通过jinja判断是否添加checked属性,代码更简洁易维护:

...
{% block content %}
    <h1>{% block title %} Title {% endblock %}</h1>
    <form method="POST" action="{{ url_for('index') }}">
         <div class="custom-control custom-switch">
             <input type="checkbox" name="switch" onclick="this.form.submit()" value="1" class="custom-control-input" id="customSwitch1" {{ 'checked' if switchcheck == 1 else '' }}>
             <label class="custom-control-label" for="customSwitch1">Active</label>
         </div>
    </form>
    {% for row in rows %} 
...

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 19:54:03