首页 > 解决方案 > 用简单的形式烧瓶 BadRequest

问题描述

嘿 !

使用来自获得 werkzeug.exceptions.BadRequestKeyError KeyError: 'first' 的简单表单的输入时遇到一些问题

HTML

  <body>
    <form id="inform" method="POST">
      User name:<input name="first" type=text>
      message:<input name="second" type=text>
      <input id="sendBtn" type="button" value="send">
    </form>
    <pre id="chatbox">Loading...</pre>
  </body>

Python

today=date.today()
app=Flask(__name__)
app.static_folder = 'static'

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

@app.route("/<room>",methods=['GET'])
def second(room):
    return render_template('index.html')

@app.route("/chat/<room>",methods=['GET','POST'])
def third(room):
    if request.method == "GET":
        pass
    elif request.method == "POST":
        name = request.form["first"]
        massage = request.form["second"]
        now = datetime.now()
        dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
        f=open(f"chat room {room}", "w")
        f.write(f"room number {room}\ndate and time {dt_string}\nusername {name} massage {massage}")
        f.close()
    return render_template('index.html')


if __name__=="__main__":
    app.run(host="0.0.0.0",debug=True)

收到此错误:

10.0.0.4 - - [18/May/2021 11:03:02] "POST /api/chat/5454 HTTP/1.1" 404 -

谢谢您的帮助 !

标签: pythonhtmlformsflask

解决方案


您的功能third导致此错误。由于您同时允许GETPOST方法,因此您必须分别处理它们。GET请求不包含任何表单变量,这正是它引发错误的原因。

因此,您可以使用条件对不同的方法执行不同的操作:

@app.route("/chat/<room>", methods=['GET', 'POST'])
def third(room):
    if request.method == "GET":
        # do something
    elif request.method == "POST":
        # do something else

    return render_template('index.html')

您可以将当前third函数的所有内容放在elif此代码块中。


推荐阅读