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.
I think there's no general solution to this, and different approaches are suited for different overall scenarios. Let me propose two:
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
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.