0

是否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

4

1 回答 1

1

截至目前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)
于 2019-05-22T08:29:49.407 回答