Validation for custom type in Cerberus

白昼怎懂夜的黑 提交于 2020-06-25 05:25:25

问题


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.



来源:https://stackoverflow.com/questions/50258249/validation-for-custom-type-in-cerberus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!