Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

python - Cast Flask form value to int

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 a ValueError in the log and Flask will return a 500 response. And if the form didn't have a personId key, Flask will return a 400 error.

personId = int(request.form['personId'])

Instead you can use the MultiDict.get() method and pass type=int to get the value if it exists and is an int:

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.


There are also some issues with your example route.

A route should return something, otherwise it will raise a 500 error. print outputs to the console, it doesn't return a response. For example, you could return the id again:

@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 not needed in Python and in this case are 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...