首页 > 解决方案 > 是否可以在棉花糖中定义具有互斥字段的嵌套模式?

问题描述

我正在使用棉花糖来验证我在烧瓶 restful api 中收到的 json 数据。然而,在post请求中有一个互斥字段
例如 : {"predict": {"id": "5hgy667y4h7f"}}or {"predict": {"text": "This is a sample sentence"}}
But NOT both idandtext应该一起发送。此外,根据天气调用idtext接收不同的方法。

问)我如何在棉花糖中构建一个允许我验证上述内容的模式?

我为任一字段提供的示例代码如下 -

from flask import Flask, request
from flask_restful import Resource, Api, abort
from marshmallow import Schema, fields, ValidationError
app = Flask(__name__)
api = Api(app)

class Mutex1(Schema):
    text = fields.Str(required=True)
    class Meta:
        strict = True

class Mutex2(Schema):
    id_ = fields.Str(required=True)
    class Meta:
        strict = True

class MySchema(Schema):
    predict = fields.Nested(Mutex1)
    class Meta:
        strict = True

class Test(Resource):
    def post(self):
        input_req = request.get_json(force=True)
        try:
            result = MySchema().load(input_req)
        except ValidationError:
            return {'message': 'Validation Error'}, 500
        else:
            return {'message': 'Successful validation'}, 200

api.add_resource(Test, '/test')
app.run(host='0.0.0.0', port=5000, debug=True)

此代码仅接受texttextwith id_,但仅拒绝id_。知道如何让它接受id_和拒绝两者text以及id_何时一起通过吗?

标签: pythonpython-3.xflaskflask-restfulmarshmallow

解决方案


使用两者创建一个Mutex模式,textid_添加模式级验证以失败,如果两者都提供。

class Mutex(Schema):

    @validates_schema
    def validate_numbers(self, data):
        if (
               ('text' in data and 'id_' in data) or
               ('text' not in data and 'id_' not in data)
           ):
            raise ValidationError('Only one of text and _id is allowed')

    text = fields.Str()
    id_ = fields.Str()
    class Meta:
        strict = True

旁注:

  • 输入验证错误不应返回 500(服务器错误)而是 422。
  • 我不熟悉flask-restful,但看起来你可以通过使用webargs来解析资源输入来为自己节省一些样板文件。

推荐阅读