Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify that an argument is optional in flask-restful

I have code like this:

def delete(self, rid):
    parser = reqparse.RequestParser()
    parser.add_argument('rating', default=2, type=int, help='blablabla')
    args = parser.parse_args()

    rating = args['rating']
    ...
    return {'message': message}

This still asks me for the rating param, and throws 400 Bad Request if no exist.

Did I miss something?

like image 872
hbrls Avatar asked Dec 17 '13 10:12

hbrls


People also ask

What is Reqparse in flask RESTful?

With resources defined and everything connected with Blueprints, it's time to handle incoming arguments. Flask-RESTful provides a solid tool known as Reqparse for specifying and validating submitted data.

Is Reqparse deprecated?

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

Which of the following modules of Flask_restful is used for parsing request arguments?

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.

What is resource in Flask_restful?

resource ( Type[Resource] ) – the class name of your resource. urls (str) – one or more url routes to match for the resource, standard flask routing rules apply. Any url variables will be passed to the resource method as args. endpoint (str) – endpoint name (defaults to Resource.


1 Answers

Try required=False:

parser.add_argument('rating', default=2, required=False, type=int, help='blablabla')

and check for rating in args (if 'rating' in args: pass).

like image 170
orange Avatar answered Dec 29 '22 01:12

orange