1

I wondered if there is a way to pass a dict to the arguments of a RequestParser .add_argument() command

it normally works like this

    my_parser = reqparse.RequestParser()
    my_parser.add_argument('my_field', type=dict, help='my_field must be a dict', required=True)

For code re-usability purposes, I'd like to use it somewhat like this

    my_arguments = {type=dict, help='my_field must be a dict', required=True}

and then pass these as arguments to the .add_argument function using:

    my_parser.add_argument('my_field', my_arguments)

I got stuck trying to do this using list comprehension,

    my_parser.add_arguments('my_field', list(key=value for (key, value) in parser_arguments.items()))

at which point I realized I probably can't use a dict, might need to do a getattr() and clearly investing too much time on this. It seems possible and elegant to me, but I can't find a solution anyway, thankful for any enlightening ideas on this.

Edit: I can't use the intuitive

    my_parser.add_argument('my_field', my_arguments)

because the dict will be added to the "default" field of the parser argument, and the actual fields ("type", "help" and "required") are unaffected.

c8999c 3f964f64
  • 1,430
  • 1
  • 12
  • 25
  • Possible duplicate of [RESTful-Flask parsing JSON Arrays with parse\_args()](https://stackoverflow.com/questions/45613160/restful-flask-parsing-json-arrays-with-parse-args) – ycx Oct 28 '19 at 14:34

1 Answers1

1

You can use kwargs unpacking:

my_arguments = {'type':dict, 'help':'my_field must be a dict', 'required':True}
my_parser.add_argument('my_field', **my_dict)

Which is equivalent to

my_parser.add_argument('my_field', type=dict, help='my_field must be a dict', required=True)
Nico Griffioen
  • 5,143
  • 2
  • 27
  • 36