在flask-restful中解析整数列表
我正在使用烧瓶稳定,但在构建
I'm using the flask-restful, and I'm having trouble constructing a RequestParser
that will validate a list of only integers. Assuming an expected JSON resource format of the form:
{
'integer_list': [1,3,12,5,22,11, ...] # with a dynamic length
}
...然后将使用类似以下形式的表单创建一个RequestParser:
... and one would then create a RequestParser using a form something like:
from flask.ext.restful import reqparse
parser = reqparse.RequestParser()
parser.add_argument('integer_list', type=list, location='json')
...但是我如何验证是整数列表?
... but how can i validate is an integer list?
您可以使用isinstance检查类型,这里将类型设置为int(整数).
You can check types with isinstance, here you set the type to int (integer).
这将像这样工作:
a=1
isinstance(a,int)
计算为TRUE
要检查整个列表,请使用all().并使用for循环遍历列表,以便检查列表中的每个元素.
To check this for a whole list use all(). and loop through the list with the for loop so every element of the list gets checked.
if all(isinstance(x,int) for x in integer_list):
parser.add_argument('integer_list', type=list, location='json')
在您的情况下,如果所有元素都是整数,则应求值为TRUE,并在for循环中执行代码
In your case this should evaluate to TRUE if all elements are integers and executes the code in the for loop