Search code examples
pythonvalidationcerberus

Cerberus META validation rule access


Python cerberus has a validation rule called meta where I assign a dict to meta rule. How am i supposed to access it? I am writing a custom error_handler using this to customise the error messages.

My target is schema = {'a': {'type': 'integer', 'meta': {'label': 'Age'}}} and would like to use the label in my error message.

Any help would be appreciated.


Solution

  • Answering my own question.

    I created a custom error_handler to prepend the label to my error messages.

    from cerberus.errors import BasicErrorHandler
    
    class CustomErrorHandler(BasicErrorHandler):
        def __init__(self, schema):
            self.custom_defined_schema = schema
    
        def _format_message(self, field, error):
            return self.custom_defined_schema[field].get('meta', {}).get('label', field) + ': ' + super(CustomErrorHandler, self)._format_message(field, error)
    
    val = Validator(schema, error_handler=CustomErrorHandler(schema))
    

    Hopefully it'll help the future users.