将Flask表单值转换为int [英] Cast Flask form value to int
问题描述
@ app.route('/ getpersonbyid',methods = ['POST'])
def getPersonById():
personId =(int)(request.form ['personId'])
print personId
我在RESTClient中通过POST发送数据personId。但是我没有得到结果。我得到一个400错误的请求错误。
在我的代码中有错误吗?如果是这样的话,当请求数据是通过POST的时候我怎么得到具体的数据。
你想返回 em>您的 personId
值;打印到控制台将无助于Web应用程序: @ app.route('/ getpersonbyid',methods = ['POST'])
get getPersonById():
personId = int(request.form ['personId'])
return str(personId)#返回一个字符串以产生一个合适的响应
围绕 int
的括号是无意义的噪音,顺便说一下,它们在Python中是不需要的,在这种情况下,解析器会忽略它。
我假设你正在做一些有意义的 personId
在视图中的值;否则使用 int()
这个值是没有意义的。
你也可以使用 MultiDict.get()
方法为您的值进行转换:
pre $ person $ id $ request.form.get('personId',type = int)
现在设置 personId
如果该字段不在表单中,或者不能转换为整数,则为整数或 None
。
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; I get a 400 Bad Request error instead.
Is there an error in my code? If so how do I get specific data when the request data is via POST.
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.
这篇关于将Flask表单值转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!