【问题标题】:Python Marshmallow condition based validationPython Marshmallow 基于条件的验证
【发布时间】:2020-09-04 06:12:40
【问题描述】:

这是我的代码

from marshmallow import Schema, fields,ValidationError,INCLUDE


class userschema(Schema):
    name = fields.String()
    gender = fields.String()
    age = fields.Integer(validate=Range(min=18, max=100))

def user_check(user):
    try:
        validate = userschema().load(user,unknown=INCLUDE)
        print(validate)
    except ValidationError as err:
        print(err.messages)


user_1 = {"name":"priya","gender":"female","age":20}
user_2 = {"name":"gowtham","gender":"male","age":50}

user_check(user_1)

有什么方法可以验证男性最低要求 21 岁和女性最低要求 18 岁的年龄

【问题讨论】:

    标签: python marshmallow


    【解决方案1】:

    您使用的验证器 (validate.Range)。它将验证男性和女性的每个用户。对于您的情况,您需要一个自定义验证器功能。使用类似的东西。

    # other imports
    from marshmallow import validates_schema
    
    class UserSchema(Schema):
        name = fields.String()
        gender = fields.String()
        age = fields.Integer()
        
        @validates_schema
        def validate_age(self, data, **kwargs):
            if data['gender'] == 'male':
                if data['age'] < 21:
                    raise ValidationError("Minimum age for males is 21.")
    
            if data['gender'] == 'female':
                if data['age'] < 18:
                    raise ValidationError("Minimum age for females is 18.")
    

    参考资料: https://marshmallow.readthedocs.io/en/latest/extending.html#schema-level-validation

    【讨论】:

    • 谢谢,有什么方法可以在不使用 validates_schema 的情况下使用 marshmallow 验证器验证年龄,例如 field.Int(validate.Range(min=21)) 用于男性 field.Int(validate.Range (min=18)) 女性
    • 我不这么认为,因为您的要求基于序列化程序的其他一些字段。 AFAIK 你不能通过简单的 validate.Range 或类似的东西来做到这一点。
    • 如果它确实解决了您的问题,请为答案投票。谢谢。
    猜你喜欢
    • 2023-03-26
    • 2020-06-15
    • 2018-03-09
    • 1970-01-01
    • 2011-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-12
    相关资源
    最近更新 更多