Python 通过表单在 Flask 上发布数据给出 400 Bad Request

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19578613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:05:39  来源:igfitidea点击:

Posting Data on Flask via form is giving 400 Bad Request

javascriptpythonhtmlhttpflask

提问by Rahul

I am trying to post data via my front end and the flask app is throwing 400 bad request. However If I am doing the same using Curl call it seems to work fine. I dont know what I am missing in the form.

我正在尝试通过我的前端发布数据,而 Flask 应用程序抛出了 400 个错误的请求。但是,如果我使用 Curl 调用做同样的事情,它似乎工作正常。我不知道我在表格中缺少什么。

The following is my form code

以下是我的表单代码

<script>
function sub() {
    console.log('sub function');
    $("#fquery").submit();
}
</script>
<form id="form1" action="/final" method="post">
 <input id='query' type="text">
  <button type="submit" onClick='sub()'>Submit &raquo;</button>
</form>

At server side:

在服务器端:

@app.route('/final',methods=['POST','GET'])
def message():
    if request.method == 'POST':
        app.logger.debug(" entered message function"+ request.form['query'])
        q = request.form['query']
    return render_template('final.html',query=q,result="Core_Table Output")

The server side seems fine to me. Since I am getting response for curl request

服务器端对我来说似乎很好。由于我收到 curl 请求的响应

curl http://localhost:8000/final -d "query=select starct st blah blah" -X POST -v
*   Trying 127.0.0.1... connected
> POST /gc HTTP/1.1
> User-Agent: curl/7.22.0 (i686-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3
> Host: localhost:8000
> Accept: */*
> Content-Length: 41
> Content-Type: application/x-www-form-urlencoded
> 
* upload completely sent off: 41out of 41 bytes
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Content-Type: text/html; charset=utf-8
< Content-Length: 1961
< Server: Werkzeug/0.9.4 Python/2.7.3
< Date: Thu, 24 Oct 2013 23:33:12 GMT

采纳答案by Robin Krahl

Ah, I think I see it: You only set the idbut not the namefor the inputelement. Yet the nameis used in the form data that is sent to the server. This causes a KeyErrorat request.form['query']which causes the 400 error.

啊,我想我明白了:你只为元素设置了id而不是。然而用于发送到服务器的表单数据。这导致在这导致400错误。nameinputnameKeyErrorrequest.form['query']

回答by Jerry

Besides what @Robin Krahl said, You also should add enctype="multipart/form-data"in your form. So the code maybe like this:

除了@Robin Krahl 所说的,您还应该enctype="multipart/form-data"在表单中添加。所以代码可能是这样的:

<form id="form1" action="/final" method="post" enctype="multipart/form-data">
   <input id='query' type="text">
   <button type="submit" onClick='sub()'>Submit &raquo;</button>
</form>"