Python 基于 Marshmallow 条件的验证

Python Marshmallow condition based validation

这是我的代码

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 岁的年龄

您使用的验证器(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