在flask-restful中解析整数列表 [英] Parsing a list of integers in flask-restful

查看:353
本文介绍了在flask-restful中解析整数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用烧瓶稳定,但在构建将验证仅整数的列表.假设期望的JSON资源格式为:

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

这篇关于在flask-restful中解析整数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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