I have a form that posts a personId int to Flask. However, request.form['personId'] returns a string. Why isn’t Flask giving me an int?
I tried casting it to an int, but the route below either returned a 400 or 500 error. How can I get I get the personId as an int in Flask?
@app.route('/getpersonbyid', methods = ['POST'])
def getPersonById():
personId = (int)(request.form['personId'])
print personId
HTTP form data is a string, Flask doesn’t receive any information about what type the client intended each value to be. So it parses all values as strings.
You can call
int(request.form['personId'])to get the id as an int. If the value isn’t an int though, you’ll get aValueErrorin the log and Flask will return a 500 response. And if the form didn’t have apersonIdkey, Flask will return a 400 error.Instead you can use the
MultiDict.get()method and passtype=intto get the value if it exists and is an int:Now
personIdwill be set to an integer, orNoneif the field is not present in the form or cannot be converted to an integer.There are also some issues with your example route.
A route should
returnsomething, otherwise it will raise a 500 error.printoutputs to the console, it doesn’t return a response. For example, you could return the id again:The parenthesis around
intare not needed in Python and in this case are ignored by the parser. I’m assuming you are doing something meaningful with thepersonIdvalue in the view; otherwise usingint()on the value is a little pointless.