Validation for custom type in Cerberus

2020-07-20 04:01发布

问题:

I really enjoy Cerberus but I can't figure out a simple case in the docs. I want to have the type fudge which is a string with ~ prepended. I simply can't figure out how to do it..

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

This seems like a simple case.. so it feels I am doing something totally wrong.

回答1:

In Cerberus 1.2 you can achieve this like below:

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)

So no need to hack around with TypeDefinition.