Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a list of integers in 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
}

... 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?

like image 441
Ricardo Avatar asked Jan 03 '15 19:01

Ricardo


People also ask

Is flask RESTful deprecated?

It seems like Flask-Restful isn't actively maintained anymore according to https://github.com/flask-restful/flask-restful/issues/883, which lists alternatives, including Marshmallow in place of reqparse.

What is Reqparse in flask RESTful?

Flask-RESTful's request parsing interface, reqparse , is modeled after the argparse interface. It's designed to provide simple and uniform access to any variable on the flask. request object in Flask.

Is Reqparse deprecated?

reqparse has been deprecated (https://flask-restful.readthedocs.io/en/latest/reqparse.html):

What is parser in flask?

Parsers are responsible for taking the content of the request body as a bytestream, and transforming it into a native Python data representation. Flask API includes a few built-in parser classes and also provides support for defining your own custom parsers.


1 Answers

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.

like image 78
oferei Avatar answered Sep 28 '22 11:09

oferei