flask-输入数据比@ api.expect更严格吗? [英] flask - something more strict than @api.expect for input data?

查看:57
本文介绍了flask-输入数据比@ api.expect更严格吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的flask-restplus API中,我不仅要检查输入数据,就像下面的示例一样

In my flask-restplus API I'd like not only to check that input data, like in the following example

resource_fields = api.model('Resource', {
    'name': fields.String(default = 'string: name', required = True),
    'state': fields.String(default = 'string: state'),
})

@api.route('/my-resource/<id>')
class MyResource(Resource):
    @api.expect(resource_fields, validate=True)
    def post(self):
        ...

必须具有名称"字段,并且可能具有状态"字段,还要检查是否没有其他字段(如果发生这种情况,则会引发错误).还有其他装饰器吗?我可以通过自定义功能检查输入数据的正确性吗?

must have 'name' field and may have 'state' field, but also to check that there are no other fields (and to raise an error if this happens). Is there another decorator for this? Can I check the correctness of the input data by a custom function?

推荐答案

尝试使用

Instead of using a dictionary for your fields, try using a RequestParser (flask-restplus accepts both as documented here. That way, you can call parser.parse_args(strict=True) which will throw a 400 Bad Request exception if any unknown fields are present in your input data.

my_resource_parser = api.parser()
my_resource_parser.add_argument('name', type=str, default='string: name', required=True)
my_resource_parser.add_argument('state', type=str, default='string: state')

@api.route('/my-resource/<id>')
class MyResource(Resource):
    def post(self):
        args = my_resource_parser.parse_args(strict=True)
        ...

有关如何在资源中使用request_parser的更多指导,请查看 flask-restplus存储库中的ToDo示例应用程序.

For more guidance on how to use the request_parser with your resource, check out the ToDo example app in the flask-restplus repo.

这篇关于flask-输入数据比@ api.expect更严格吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆