3

我真的很喜欢 Cerberus,但我无法在文档中找到一个简单的案例。我想要fudge一个带有~前缀的字符串类型。我根本不知道该怎么做..

fudge_type = cerberus.TypeDefinition('fudge_type', (str,), ())

class MyValidator(cerberus.Validator):
    types_mapping = cerberus.Validator.types_mapping.copy()
    types_mapping['fudge'] = fudge_type

    def __init__(self, *args, **kwargs):
        if 'additional_context' in kwargs:
            self.additional_context = kwargs['additional_context']
        super(MyValidator, self).__init__(*args, **kwargs)

    @property
    def additional_context(self):
        self._error(field, "INVALID!")
        return self._config.get('additional_context', 'bar')

    def _validate_type_fudge(self, field, value):
        self._error(field, "INVALID!")
        make_use_of(self.additional_context)

validator = MyValidator()
validator.validate({'name': 'yada'}, {'name': {'type': 'fudge'}})  # => True

这似乎是一个简单的案例..所以感觉我在做完全错误的事情。

4

1 回答 1

4

在 Cerberus 1.2 中,您可以像下面这样实现:

import cerberus

SCHEMA = {
    'fudge': {
        'type': 'mytype'
    }
}

class MyValidator(cerberus.Validator):
    def _validate_type_mytype(self, value):
        if value.startswith('~'):
            return True

validator = MyValidator()
validator.validate({'fudge': 'yada'}, SCHEMA)

所以没有必要乱搞TypeDefinition.

于 2018-05-10T10:49:05.873 回答