Amritha Dilip Amritha Dilip - 4 years ago 143
JSON Question

Retrieving specific POST data in Flask

I'm trying to get the post data in flask

@app.route('/getpersonbyid', methods = ['POST'])
def getPersonById():
personId = (int)(request.form['personId'])
print personId

I'm sending the data "personId" via POST in RESTClient. But i'm not getting the result.
Is there an error in the code? If so how do I get specific data when the request data is via POST.I'm new to flask, so can anybody give a solution to this?

Answer Source

You want to return your personId value; printing it to the console won't help in a web application:

@app.route('/getpersonbyid', methods = ['POST'])
def getPersonById():
    personId = int(request.form['personId'])
    return str(personId)  # back to a string to produce a proper response

The parenthesis around int are meaningless noise, btw, they are not needed in Python and are in this case ignored by the parser.

I'm assuming you are doing something meaningful with the personId value in the view; otherwise using int() on the value is a little pointless.

You can also use the MultiDict.get() method to have the value converted for you:

personId = request.form.get('personId', type=int)

Now personId will be set to an integer, or None if the field is not present in the form or cannot be converted to an integer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download