我正在尝试在 Python 中使用 Cerberus 来验证一些数据。
我发现对于“boolean ”类型,验证器总是返回 True,如下所示:
import cerberus
bool_schema = {'name': {'type': 'boolean', 'required': True}}
cerberus.schema_registry.add('bool_schema', bool_schema)
v = cerberus.Validator({'name': {'schema': 'bool_schema'}})
test1 = {'name': 'a'}
test2 = {'name': 0}
print(v.validate(test1))
print(v.validate(test2))
上面的代码打印两个 True。
实际上,我需要的是验证该值是 True 还是 False(Python 中的 bool 类型),其他值不应通过验证器。
最佳答案
这是一个语义问题。尽管您没有明确指定要实现的目标,但我假设您想要测试映射到字典中 name
的值是否为 boolean 值并确保它存在。
在示例代码的第 4 行中,您定义了一个架构,该架构引用架构注册表中先前定义的架构。验证时它将被解释为
{'name':
{'schema': {
{'type': 'boolean',
'required': True}
}}}
仅处理二级schema
规则if the value of name
is a mapping 。在您的每个示例中,情况并非如此,这将有效地根本不处理任何规则,因此验证每次都会返回 True
。
为了回答我上面假设的问题,这将涵盖它:
import cerberus
required_boolean = {'type': 'boolean', 'required': True}
cerberus.rules_set_registry.add('required_boolean', required_boolean)
v = cerberus.Validator({'name': 'required_boolean'})
关于python - 在 Python 中使用 cerberus 验证 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41699452/