Have required set to True by default in cerberus

595 views Asked by At

Is there a way to tell cerberus to have required set to True by default for all keys in the schema? This would save me some time, because most often I want to assert the existence of a key.

1

There are 1 answers

0
funky-future On BEST ANSWER

I think there's no general solution to this, and different approaches are suited for different overall scenarios. Let me propose two:

Extending the schema

This is fairly simple, just add the required rule to all fields of a schema before employing it:

for field in schema:
    field['required'] = True

Custom validator

As the Validator class has a method that checks all fields in regard to this rule, it can be overridden in a subclass:

from cerberus import errors, Validator


class MyValidator(Validator):
    def __validate_required_fields(self, document):
        for field in self.schema:
            if field not in document:
                self._error(field, errors.REQUIRED_FIELD)

Note that this proposal doesn't consider the excludes rule as the original implementation.

However, as this is part of the non-public methods, the underlying design might change unannounced in the future.