0

我想允许一个字段为空,但当它不为空时,我希望它是整数并检查范围。我需要将字段强制转换为 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']}]}]}
4

1 回答 1

0

我没有评论的声誉,我知道这不是一个好的答案,但我不确定该放在哪里。

您收到该错误的原因是因为coerce它不是规则上下文中的有效oneof规则。根据文档coerce被认为是规范化规则,并且在任何规则中都不允许这样做*of

我知道这不是一个好的解决方案,但您可以使用check_with规则并编写自定义验证函数。然后在该函数中,您可以简单地转储其中的所有检查逻辑。像这样的东西:

def validate_age(f, v, e):
    # Perform your checks

my_schema = {
    "name": {
        "type": "string",
        "minlength": 2
    },
    "age": {
        "check_with": validate_age
    }
}
于 2022-01-06T00:11:02.413 回答