【问题标题】:Using cerberus in Python to validate boolean values在 Python 中使用 cerberus 验证布尔值
【发布时间】:2017-06-01 15:40:13
【问题描述】:

我正在尝试在 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 类型),其他值不应该通过验证器。

【问题讨论】:

  • 您使用的是哪个版本的cerberus?上面的代码会导致错误(“raise SchemaError(self.schema_validator.errors) cerberus.schema.SchemaError: {'name': [{'schema': [{'anyof': ['no definitions validate', {'anyof definition 1': ['Rules set definition boolean not found.'], 'anyof definition 0': ['Schema definition boolean not found.']}]}]}]}”与cerberus 1.0.1 是最新的。
  • 我通过pip 安装了cerberus,而cerberus.__version__ 显示它正是1.0.1 版
  • 抱歉,我在问题中写错了,Validator 中的架构名称是 'bool_schema' 而不是 'schema'

标签: python validation boolean schema cerberus


【解决方案1】:

这是一个语义问题。尽管您没有明确指定要实现的目标,但我假设您要测试映射到字典中 name 的值是否为布尔值并确保它存在。

在示例代码的第 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'})

【讨论】:

  • 我明白了。 schema_registry 表示验证该位置的整个 dict
【解决方案2】:

可能是架构注册表的问题(我打开了ticket,以便我们进一步调查 - 将在此处报告)。

与此同时,您可以跳过注册表,它会正常工作:

from cerberus import Validator

schema = {'name': {'type': 'boolean', 'required': True}}

v = Validator()
v.validate({'name': 'a'})
False

v.errors
{'name': ['must be of boolean type']}

为未来的读者编辑:下面@funky-future 的答案实际上解释了您的代码失败的原因以及如何修复它。

【讨论】:

  • 或许删除这个答案会更好?
猜你喜欢
  • 1970-01-01
  • 2014-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多