使用字典作为 RequestParser 验证参数

Using a dict as RequestParser validation arguments

我想知道是否有办法将字典传递给 RequestParser .add_argument() 命令的参数

通常是这样的

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

出于代码可重用性的目的,我想像这样使用它

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

然后将这些作为参数传递给 .add_argument 函数,使用:

    my_parser.add_argument('my_field', my_arguments)

我在尝试使用列表理解来执行此操作时遇到了困难,

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

此时我意识到我可能无法使用字典,可能需要执行 getattr() 并且显然在这上面投入了太多时间。对我来说这似乎是可行且优雅的,但我还是找不到解决方案,感谢对此有任何启发性的想法。

编辑:我无法使用直觉

    my_parser.add_argument('my_field', my_arguments)

因为字典将被添加到解析器参数的 "default" 字段,而实际字段("type"、"help" 和 "required")不受影响。

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)

相当于

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