【问题标题】:Cerberus and validating a list containing dictsCerberus 和验证包含字典的列表
【发布时间】:2021-05-02 23:59:00
【问题描述】:

我正在尝试验证以下文档。

document = {
            'days': {
                'Monday': [{
                    'address': 'my address',
                    'city': 'my town'
                }],
                'Tuesday': [{
                    'address': 'my address',
                    'city': 'my town'
                }]
            }
        }

使用以下架构。

    schema = {
                'days': {
                    'type': 'dict',
                    'allowed': ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
                    'schema': {
                        'type': 'list',
                        'schema': {
                            'address': {
                                'type': 'string'
                            },
                            'city': {
                                'type': 'string', 'required': True
                            }
                        }
                    }
                }
            }
v = Validator(schema)
if not v.validate(document, schema):
  raise Exception("Configuration file is not valid", v.errors)

我收到以下错误:{days: ['must be of dict type']}

我不知道如何验证列表中包含的字典。

【问题讨论】:

    标签: python cerberus


    【解决方案1】:

    你们很亲密。您可以使用valuesrules 表示“无论键是什么,这都是值的规则”。然后,在列表中,您需要一个模式,说明该列表具有 dicts,然后是元素内部的模式。可能有更简单的方法,但这会传递您的文档。

    schema = {
                'days': {
                    'type': 'dict',
                    'allowed': ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
                    'valuesrules': {
                        'type': 'list',
                        'schema': {
                            'type': 'dict',
                            'schema': {
                                'address': {
                                    'type': 'string'
                                },
                                'city': {
                                    'type': 'string', 'required': True
                                }
                            }
                        }
                    }
                }
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多