Python数据验证库Cerberus

可验证数据是否符合指定的模式,并且提供了自定义规则的功能,常见使用。

1. 安装

pip install cerberus

2. 使用代码示例(python3)

(1)基础使用

from cerberus import Validator

# 定义验证规则
schema = {
    'name': {
        'type': 'string',
        'minlength': 3,
        'maxlength': 20,
        'required': True,
    },
    'age': {
        'type': 'integer',
        'min': 0,
        'max': 120,
        'required': True
    },
    'email': {
        'type': 'string',
        'regex': r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$',
    }
}

# 创建验证器对象
validator = Validator(schema, allow_unknown=True)   # allow_unknown,未知字段不验证


# 模拟数据
data = {
    'name': 'John Doe',
    'age': 150,
    'email': 'john@example.com',
    'test': '123'
}


# 开始验证数据
if validator.validate(data):
    print("数据验证成功!")
else:
    print("数据验证失败 errors:")
    print(validator.errors) #  {'age': ['max value is 120']}
    for field, errors in validator.errors.items():
        print(f"Field '{field}': {', '.join(errors)}")

(2)验证字典格式

schema = {
    'person': {
        'type': 'dict',
        'schema': {
            'name': {'type': 'string', 'required': True},
            'age': {'type': 'integer', 'required': True},
        },
        'required': True,
    },
}

validator = Validator()

data = {
    'person': {
        'name': 'John Doe',
        'age': 30,
    },
}

if validator.validate(data, schema):
    print("数据验证成功!")
else:
    print("数据验证失败 errors:")
    print(validator.errors)

(3)自定义验证函数

def custom_validation(field, value, error):
    if len(value) < 5:
        error(field, "最少5个字符: %s " % len(value))


schema = {
    'password': {'type': 'string', 'validator': custom_validation},
}

validator = Validator(schema)

data = {
    'password': '1234'
}

if validator.validate(data):
    print("数据验证成功!")
else:
    print("数据验证失败 errors:")
    print(validator.errors)

(4)验证列表格式

schema = {
    'list_key': {
        'type': 'list',
        'schema': {
            'type': 'dict',
            'schema': {
                'name':
                    {
                        'type': 'string',
                        'required': True,
                        'empty': False
                    },
                'relationship': {
                    'type': 'string',
                    'required': True,
                    'empty': False
                }
            }
        }
    }
}

data = {"list_key": [{'name': 'Mary', 'relationship': 'sister'}, {'name': 'Tom', 'relationship': 'brother-in-law'}]}

validator = Validator(schema)

if validator.validate(data):
    print("数据验证成功!")
else:
    print("数据验证失败 errors:")
    print(validator.errors)

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值