Python Cerberus 对嵌套列表级别的依赖
Python Cerberus dependencies on nested list level
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
为真时存在。我如何将其翻译成 Cerberus
?
截至目前 Cerberus 1.2
不支持此功能。为了实现此功能,我已经覆盖了 Validator
class 方法 _lookup_field
。
这是 link 对 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)
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
为真时存在。我如何将其翻译成 Cerberus
?
截至目前 Cerberus 1.2
不支持此功能。为了实现此功能,我已经覆盖了 Validator
class 方法 _lookup_field
。
这是 link 对 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)