简体   繁体   English

Cerberus 和验证包含字典的列表

[英]Cerberus and validating a list containing dicts

I'm trying to validatie the following doc.我正在尝试验证以下文档。

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

Using the following schema.使用以下架构。

    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)

I get the following error: {days: ['must be of dict type']}我收到以下错误:{days: ['must be of dict type']}

I cannot figure out how to validate the dict that is contained within the list.我无法弄清楚如何验证列表中包含的字典。

You were very close.你非常亲近。 You can use valuesrules to say "whatever the keys are, here's the rules for the values".您可以使用valuesrules来表示“无论键是什么,这都是值的规则”。 Then, in the list, you need a schema that says the list has dicts, then a schema inside that for the elements.然后,在列表中,您需要一个模式,说明该列表具有 dicts,然后是元素内部的模式。 There may be a simpler way to do it, but this passes your document.可能有一种更简单的方法可以做到这一点,但这会传递您的文档。

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
                            }
                        }
                    }
                }
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM