Dan*_*aig 6 python validation cerberus
我正在尝试为具有引用文档中较高位置的依赖项的文档创建模式.例如:
document = {
'packages': {
'some-package': {'version': 1}
},
'build-steps': {
'needs-some-package': {'foo': 'bar'},
'other-thing': {'funky': 'stuff'}
}
}
Run Code Online (Sandbox Code Playgroud)
我在这里苦苦挣扎的是强制build-steps.needs-some-package和packages.some-package之间的依赖关系.每当构建步骤包含"needs-some-package"时,包必须包含"some-package".
当"need-some-package"不存在时,不需要"some-package".所以这份文件也应该验证.
other_document = {
'packages': {
'other-package': {'version': 1}
},
'build-steps': {
'other-thing': {'funky': 'stuff'}
}
}
Run Code Online (Sandbox Code Playgroud)
具有依赖关系的模式似乎是合适的位置
schema = {
'packages': {
'type': 'dict',
'valueschema': {
'type': 'dict'
}
},
'build-steps': {
'type': 'dict',
'schema': {
'needs-some-package': {
'type': 'dict',
'dependencies': 'packages.some-package'
},
'other-thing': {
'type': 'dict'
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
但这不起作用,因为似乎Cerberus正在"构建步骤"下的子文档中寻找"包".有没有办法上升文档树?或者引用一些关于文档根目录的内容?
所描述的问题已在版本 1.0.2 中得到解决:
处理子文档时,将从该文档级别开始查找相关字段。为了将处理后的文档定位为根级别,声明必须以 ^ 开头。出现两个初始插入符 (^^) 会被解释为字面意思,单个 ^ 没有特殊含义。
示例代码:
import cerberus
schema = {
'packages': {
'type': 'dict',
'valueschema': {
'type': 'dict'
}
},
'build-steps': {
'type': 'dict',
'schema': {
'needs-some-package': {
'type': 'dict',
'dependencies': '^packages.some-package'
},
'other-thing': {
'type': 'dict'
}
}
}
}
document = {
'packages': {
'some-package': {'version': 1}
},
'build-steps': {
'needs-some-package': {'foo': 'bar'},
'other-thing': {'funky': 'stuff'}
}
}
validator = cerberus.Validator(schema)
print(validator.validate(document))
Run Code Online (Sandbox Code Playgroud)