Flask Bad Request Error;由于多个POST请求而出现问题

时间:2018-06-08 01:49:46

标签: python html flask jinja2

 <form method = "POST">
         <div class=" col-lg-4 col-lg-4 col-lg-4 col-lg-4">
            <div class="box">
                <input type="text" name="image-url" placeholder="Image URL Link"style="color:black" required="required" value = "new"/>
              <textarea cols=80 rows=4 style="color:black" name = "description" placeholder="Place your description here" value = "new"></textarea>
                <button type="submit">Upload</button>
                </div>
             </div>
            </form>                
    {% for i in range(amount_of_images) %}
         <div class=" col-lg-4 col-lg-4 col-lg-4 col-lg-4">
              <div class="box">
                <img src="{{image[i]}}" alt="view" width = "300" height = "300"/>
            <form method = "POST">
                <textarea cols=80 rows=4 style="color:black" name = "update-description" value = "update">{{description[i]}}</textarea>
                    <button type="submit">Update Description</button>
            </form>

以上是我的HTML / Jinja代码

@app.route("/gallery-manager", methods = ["GET", "POST"])
def gallery_manager():
if request.method == "POST":    
    if(request.form["image-url"] and request.form["description"]) is not None:
        model.add_new_image(request.form["image-url"], request.form["description"])
        id, image, description, amount_of_images = model.get_gallery()
        return render_template("gallery-manager.html", image = image, description = description, amount_of_images = amount_of_images, id = id)


    if request.form['update-description'] is not None:
        print("hello")



id, image, description, amount_of_images = model.get_gallery()
return render_template("gallery-manager.html", image = image, description = description, amount_of_images = amount_of_images, id = id)

以上是我的Python / Flask Code ...

问题是,当我点击更新说明提交按钮,即html代码中处理的第二个POST时,我收到400错误

Bad Request
The browser (or proxy) sent a request that this server could not understand.

我意识到当其中一个POST字段为空且无法找到时会发生此错误。我知道发生这种情况是因为当我点击第二个POST提交按钮时,它会运行第一次POST检查(request.form [“image-url”]等,并发现它满足因此想要运行该代码,但不能因为更新描述仍然是空的。我该如何避免这种情况。

换句话说,我该如何处理多种POST方法。

谢谢,

1 个答案:

答案 0 :(得分:0)

这是因为您缺少表单应发送请求的表单中的操作部分

<form  action="/whereYouWantToSendRequest" method="post">

通过在上面替换它来添加您的url端点 的 whereYouWantToSendRequest

这是两个请求

  <input type="text" name="image-url" value = "new"/>
    <input type="text" name="update-description" value = "update"/>

并找出哪个请求

if request.form["image-url"] == "new":
     somethinggg
elif request.form["update-description"] =="update":
     sommmm