Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Posting Data on Flask via form is giving 400 Bad Request

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.

The following is my form code

<script>
function sub() {
    console.log('sub function');
    $("#form1").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 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
like image 914
Rahul Avatar asked Oct 24 '13 23:10

Rahul


2 Answers

Ah, I think I see it: You only set the id but not the name for the input element. Yet the name is used in the form data that is sent to the server. This causes a KeyError at request.form['query'] which causes the 400 error.

like image 152
Robin Krahl Avatar answered Sep 19 '22 05:09

Robin Krahl


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

<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>"
like image 32
jerryleooo Avatar answered Sep 17 '22 05:09

jerryleooo