【问题标题】:In Cerberus can you use 'valueschema' with a type of 'dict'?在 Cerberus 中,您可以将“valueschema”与“dict”类型一起使用吗?
【发布时间】:2017-10-24 21:39:16
【问题描述】:

所以我使用 Cerberus 进行架构验证,但我在验证密钥未知的字典的子字典时遇到了问题。

假设我有以下文件:

dict = {
   'things': {
       '0463': {
           'foo': 'blah',
           'bar': 'bleep'
        },
        '0464': {
           'foo': 'x',
           'bar': 'y'
        },
        'another_random_id': {
           'foo': 'blah',
           'bar': 'bleep'
        }
}

所以我想验证子字典是否具有特定的结构(foobar 作为键),但我无法在不知道键的情况下找到一种验证方法(在我的case 是随机 id。我认为这是 valueschema 的一个很好的用途,但我似乎无法让 valueschema 与“dict”类型的东西一起使用。我尝试在 cerberus 中设置以下模式:

schema = {
    'things': {
        'type': 'dict',
        'valueschema': {
             'type': 'dict',
             'foo': {'type': 'string'},
             'bar': {'type': 'string'}
         }
     }
}

我是否错误地定义了我的架构,或者这对于valueschema 的当前实现是不可能的。我在存储库中看到了一些使用 valueschema 的测试,但它们只测试 valueschema 的类型是 int 或 string。

【问题讨论】:

  • 如果这仍然是一个问题,请打开一个错误报告,其中包含对您遇到的和预期的行为的描述。

标签: python cerberus


【解决方案1】:

所以我发现如果我在 valueschema 键之后放置一个 schema 字段,那么如果我在 valueschema 键之后放置一个 schema 字段,那么 cerberus 将处理 valueschema 类型。所以我的结构应该是:

schema = {
    'things': {
        'type': 'dict',
        'valueschema': {
             'type': 'dict',
             'schema':{
                 'foo': {'type': 'string'},
                 'bar': {'type': 'string'}
             }
         }
     }
}

现在仍有一些奇怪之处,因为 valueschema 的设计似乎没有预期它会验证 dict 类型的值。例如,当我从验证器扩展时,我必须重写 validate_valueschema 方法,以便 required 验证的行为与常规模式相同,因为当它在模式上调用 validate 时,它不会传入update 参数。所以我覆盖的validate_valueschema 看起来像这样:

def _validate_valueschema(self, schema, field, value):
    if isinstance(value, Mapping):
        for key, document in value.items():
            validator = self._Validator__get_child_validator()
            validator.validate(
                {key: document}, {key: schema}, 
                context=self.document, update=self.update)
            if len(validator.errors):
                self._error(field, validator.errors)

update=self.update 是我添加的所有内容。

【讨论】:

  • 不确定我是否误解了文档,因为在网站上它使用“schema”而不是“valueschema”>>> schema = { ... 'test_field': {}, ... 'a_dict' : { ... 'type': 'dict', ... 'schema': { ... 'foo': {'type': 'string'}, ... 'bar': {'type': '字符串','依赖项':'^test_field'} ... } ... } ... }
  • 0.9 版更改:将 keyschema 重命名为 valueschema。在 1.3 版中更改:将 valueschema 重命名为 valuesrules来源:docs.python-cerberus.org
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-15
  • 2020-11-23
  • 1970-01-01
  • 2014-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多