将 Flask 表单值转换为 int [英] Cast Flask form value to int

查看:53
本文介绍了将 Flask 表单值转换为 int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个将 personId int 发布到 Flask 的表单.但是,request.form['personId'] 返回一个字符串.为什么 Flask 不给我一个 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?

我尝试将其转换为 int,但下面的路由返回 400 或 500 错误.如何在 Flask 中将 personId 作为 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 表单数据是一个字符串,Flask 不会收到有关客户端希望每个值是什么类型的任何信息.因此它将所有值解析为字符串.

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.

您可以调用 int(request.form['personId']) 以获取 int 形式的 id.如果该值不是 int,您将在日志中得到 ValueError 并且 Flask 将返回 500 响应.如果表单没有 personId 键,Flask 将返回 400 错误.

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'])

相反,您可以使用 MultiDict.get() 方法 并通过 type=int 来获取值,如果它存在并且是一个整数:

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)

现在 personId 将设置为整数, None 如果该字段不存在于表单中或无法转换为整数.

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.

路由应该返回一些东西,否则会引发500错误.print 输出到控制台,它不返回响应.例如,您可以再次返回 id:

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

int 周围的括号在 Python 中是不需要的,在这种情况下被解析器忽略.我假设您正在对视图中的 personId 值做一些有意义的事情;否则在值上使用 int() 有点毫无意义.

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.

这篇关于将 Flask 表单值转换为 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆