【问题标题】:Skip default model validation in Flask Restplus在 Flask Restplus 中跳过默认模型验证
【发布时间】:2019-01-09 10:10:06
【问题描述】:

由于项目的特殊性,我必须为 Flask-restplus API 应用程序编写自己的模型验证器。简单来说——发生验证错误时,其格式和状态码(400)不正确。它应该返回带有特定格式消息的 JSON 对象,状态码为 422。

我所做的或多或少是这样的:


ns = api.namespace('somenamespace', description='blabla')

class MyModel(MyBaseModel):
    def __init__(self):
        self.id = fields.Integer()
        self.name = fields.String()


my_model = api.model('MyModel', MyModel())

@api.marshal_list_with(my_model, envelope='json')
@ns.route('/')
class SomeClass(Resource):

    @api.expect(my_model, validate=False)
    @api.doc(responses={
        200: 'Success',
        401: 'Authentication Error',
        403: 'Requested resource unavailable',
        409: 'Conflict, document already exists',
        422: 'Validation Error'
    })
    def post(self):
        """
        Save single document in the database.
        :return:
        """

        request_payload = json.loads(request.data)
        validated_payload, payload_errors = some_validation(request_payload)

        if payload_errors:
            return jsonify(payload_errors), 422
        else:
            return jsonify({'response': 'ok})
`MyModel` 的实例基本上表现得像一个字典,所以注册没有问题。问题是当我在`-d`中发送数据时,无论是通过命令行的`curl`还是swagger,我总是得到`400`而不是`422`。我认为这是由于基于“MyModel”的输入数据的默认内置验证。这很酷,但我必须省略它,并应用我自己的验证。

【问题讨论】:

  • 也许问题确实来自MyModel。您是否尝试过装饰器 api.expect 文档中描述的方式? flask-restplus.readthedocs.io/en/stable/… 它的行为是否相同?如果是这样,那么问题可能来自其他地方。另外,你能指定你在curl命令中传递的json是什么吗?
  • 感谢您的关注。当我在启动flask_restplus api 时全局关闭验证时,基本上一切都开始正常工作了。似乎如果 validate 标志设置为 True,它不会考虑来自 @api.expect 装饰器的标志。

标签: python python-3.x flask flask-restful flask-restplus


【解决方案1】:

在文档中,正如@CloC 所说,一种方法是将模型指定为

your_model = ns.model('YourModel', {
    'id': fields.Integer(
        description='The user id'
    )
    'name': fields.String(
        description='The user name'
    )
})

... > profit

@ns.route('/', methods=["post"])
@ns.doc(params={
    "id": "the user id (int)",
    "name": "the user name (str)"
})
class SomeClass(Resource):

    @ns.expect(your_model)  # this defines the request 
    # @ns.marshal_list_with(your_model, envelope='json')  # this defines the response
    @ns.response(200, 'Success')
    ... > reponses
    def post(self):
        etc...

        return <response with format as model in marshal>

您可能想要重新定义响应模型,除非您将返回您输入的表单的某些内容。也可以指定marshal_with,因为您不返回列表?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-25
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 2012-07-19
    • 1970-01-01
    相关资源
    最近更新 更多