Parsing a list of integers in flask-restful

倾然丶 夕夏残阳落幕 提交于 2019-12-05 10:12:51

You can check types with isinstance, here you set the type to int (integer).

This would work like this:

a=1    
isinstance(a,int)

evaluates to TRUE

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

In your case this should evaluate to TRUE if all elements are integers and executes the code in the for loop

You can use action='append'. For example:

parser.add_argument('integer_list', type=int, action='append')

Pass multiple integer parameters:

curl http://api.example.com -d "integer_list=1" -d "integer_list=2" -d "integer_list=3"

And you will get a list of integers:

args = parser.parse_args()
args['integer_list'] # [1, 2, 3]

An invalid request will automatically get a 400 Bad Request response.

Eric

You cannot in fact. Since you can pass a list with multiple kinds of types, e.g. [1, 2, 'a', 'b'], with reqparser, you can only parse with type=list. You need to check the elements of the list one by one by yourself. The code looks like below:

parse_result = parser.add_argument('integer_list', type=list, location='json')
your_list = parse_result.get('integer_list', [])
for element in your_list: 
    if isinstance(element, int): 
        # do something
        print "element is int"
    else:
        # do something else
        print "element is not int"

You need to use the 'append' action.

from flask.ext.restful import reqparse
parser = reqparse.RequestParser()
parser.add_argument('integer_list', type=int, action="append", location='json')

args = parser.parse_args()

list_of_int = args['integer_list']

Same issue occurred. I looked into the source code, and found Argument.type is mainly used in the situation self.type(value). So you can hack this like me:

parser.add_argument('integer_list', type=json.loads, location='json')

It's not what it supposed to do, but works.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!