在我的 Flask-restplus API 中,我不仅想检查输入数据,如下例所示
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):
...
必须有“name”字段,并且可能有“state”字段,但还要检查是否没有其他字段(如果发生这种情况,则引发错误)。
还有另一个装饰器吗?我可以通过自定义函数检查输入数据的正确性吗?
不要在字段中使用字典,而是尝试使用请求解析器 https://flask-restplus.readthedocs.io/en/stable/api.html#flask_restplus.reqparse.RequestParser(flask-restplus 接受两者记录here https://flask-restplus.readthedocs.io/en/stable/swagger.html#the-api-expect-decorator。这样你就可以调用parser.parse_args(strict=True)
这会抛出一个400 Bad Request
如果输入数据中存在任何未知字段,则例外。
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 与您的资源一起使用的更多指导,请查看待办事项示例应用程序 https://github.com/noirbizarre/flask-restplus/blob/4b58cb3e13b7720cb35a39f50d4683770ab72574/examples/todo.py#L57在 Flask-restplus 仓库中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)