我想允许一个字段为空,但当它不为空时,我希望它是整数并检查范围。我需要将字段强制转换为 int,因为它以字符串形式出现。有没有办法做到这一点?我的方法如下,但这似乎不起作用。我已经做了很多研究,但还没有看到如何在我发现的内容中做到这一点。
样本:
from cerberus import Validator
v = Validator()
v.schema = {
'name': { 'type': 'string', 'minlength': 2},
'age': {
'oneof': [
{'type': 'string', 'empty': True},
{'type': 'integer', 'min': 5, 'max': 130, 'coerce': int, 'empty': False},
]
}
}
if v.validate({'name': 'John', 'age': ''}):
print('valid data')
else:
print('invalid data')
print(v.errors)
创建验证器时出现错误:
Traceback (most recent call last):
File "<stdin>", line 6, in <module>
File "C:\Users\ken\AppData\Roaming\Python\Python36\site-packages\cerberus\validator.py", line 562, in schema
self._schema = DefinitionSchema(self, schema)
File "C:\Users\ken\AppData\Roaming\Python\Python36\site-packages\cerberus\schema.py", line 82, in __init__
self.validate(schema)
File "C:\Users\ken\AppData\Roaming\Python\Python36\site-packages\cerberus\schema.py", line 262, in validate
self._validate(schema)
File "C:\Users\ken\AppData\Roaming\Python\Python36\site-packages\cerberus\schema.py", line 278, in _validate
raise SchemaError(self.schema_validator.errors)
cerberus.schema.SchemaError: {'age': [{'oneof': [{'coerce': ['unknown rule']}]}]}