Cerberus 1.2
是否支持列表上的依赖项验证?
例如,该架构如下所示:
schema = {
'list_1': {
'type': 'list',
'schema': {
'type': 'dict',
'schema': {
'simple_field': {'type': 'boolean'},
'not_simple_field': {
'type': 'dict',
'schema': {
'my_field': {'dependencies': {'simple_field': True}}
}
}
}
}
}
}
我要检查的规则是my_field
仅在simple_field
为True时才存在。我该如何在Cerberus
中翻译?
答案 0 :(得分:0)
到目前为止Cerberus 1.2
不支持此功能。为了实现此功能,我重写了Validator
类方法_lookup_field
。
这是GitHub上功能请求的链接
这是我的实现方式
def _lookup_field(self, path: str) -> Tuple:
"""
Implement relative paths with dot (.) notation as used
in Python relative imports
- A single leading dot indicates a relative import
starting with the current package.
- Two or more leading dots give a relative import to the parent(s)
of the current package, one level per dot after the first
Return: Tuple(dependency_name: str, dependency_value: Any)
"""
# Python relative imports use a single leading dot
# for the current level, however no dot in Cerberus
# does the same thing, thus we need to check 2 or more dots
if path.startswith('..'):
parts = path.split('.')
dot_count = self.path.count('.')
context = self.root_document
for key in self.document_path[:dot_count]:
context = context[key]
context = context.get(parts[-1])
return parts[-1], context
else:
return super()._lookup_field(path)