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

Flask BadRequestKeyError求助:访问'/hi'页面返回400错误

解决Flask访问'/hi'页面的BadRequestKeyError问题

错误根源

  • GET请求访问'/hi'时,代码尝试重定向到不存在的hello视图,触发异常;且GET请求未渲染表单页面,不符合用户访问预期。
  • 直接使用request.form["inpValue"]取值,若表单提交异常(如键缺失)会直接抛出BadRequestKeyError,未做安全处理。
  • render_template(url_for('rslt', res = val))用法错误,render_template接收的是模板文件名,而非路由URL。
  • 通配符路由/<res>易与其他路由冲突,路径设计不合理。

修正后的Python代码

from flask import Flask, render_template, request, redirect, url_for

app = Flask("hello")
app.secret_key = "hello"

@app.route('/')
def home():
    return "This is a simple page. <p>Please navigate to /hi to use the input form</p>"

@app.route('/hi', methods=['POST', 'GET'])
def inp():
    if request.method == 'POST':
        # 安全获取表单值,避免键不存在抛出异常
        val = request.form.get("inpValue")
        if val:
            # 重定向到结果路由
            return redirect(url_for('rslt', res=val))
        # 输入为空时返回表单并提示
        return render_template('index.html', error="Please enter a value")
    else:
        # GET请求渲染表单页面
        return render_template('index.html')

# 更明确的结果路由,避免冲突
@app.route('/result/<res>')
def rslt(res):
    # 渲染结果模板并传入参数
    return render_template('result.html', result=res)

if __name__ == '__main__':
    app.run(debug=True)

修正后的index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">   
    <title>Input Form</title>
</head>
<body>
    <main>
        <div id="middle">
            {% if error %}
                <p style="color: red;">{{ error }}</p>
            {% endif %}
            <form action="/hi" method="post">
                <input type="text" name="inpValue" />
                <input type="submit" value="submit" />
            </form>
        </div>
    </main>
</body>
</html>

修正后的result.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Result</title>
</head>
<body>
   <p>Result = {{ result }}</p>  
</body>
</html>

关键修正说明

  • GET访问'/hi'时直接渲染表单页面,符合用户操作逻辑。
  • 用request.form.get()替代直接索引取值,避免键缺失引发的异常。
  • 修正render_template用法,通过重定向或直接传参渲染模板,逻辑更清晰。
  • 调整结果路由为/result/<res>,避免通配符路由与其他路径冲突。
  • 增加空输入的错误提示,提升用户体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 18:15:02