API Documentation¶
Validator Class¶
- class cerberus.Validator(*args, **kwargs)¶
Validator class. Normalizes and/or validates any mapping against a validation-schema which is provided as an argument at class instantiation or upon calling the
validate(),validated()ornormalized()method. An instance itself is callable and executes a validation.All instantiation parameters are optional.
There are the introspective properties
types,validators,coercers,default_setters,rules,normalization_rulesandvalidation_rules.The attributes reflecting the available rules are assembled considering constraints that are defined in the docstrings of rules’ methods and is effectively used as validation schema for
schema.- Parameters:
ignore_none_values (
bool) – Seeignore_none_values. Defaults toFalse.allow_unknown (
boolor any mapping) – Seeallow_unknown. Defaults toFalse.require_all (
bool) – Seerequire_all. Defaults toFalse.purge_unknown (
bool) – Seepurge_unknown. Defaults to toFalse.purge_readonly (
bool) – Removes all fields that are defined asreadonlyin the normalization phase.error_handler (class or instance based on
BaseErrorHandlerortuple) – The error handler that formats the result oferrors. When given as two-value tuple with an error-handler class and a dictionary, the latter is passed to the initialization of the error handler. Default:BasicErrorHandler.
- _drop_remaining_rules(*rules)¶
Drops rules from the queue of the rules that still need to be evaluated for the currently processed field. If no arguments are given, the whole queue is emptied.
- _error(*args)¶
Creates and adds one or multiple errors.
- Parameters:
args –
Accepts different argument’s signatures.
1. Bulk addition of errors:
iterable of
ValidationError-instances
The errors will be added to
_errors.2. Custom error:
the invalid field’s name
the error message
A custom error containing the message will be created and added to
_errors. There will however be fewer information contained in the error (no reference to the violated rule and its constraint).3. Defined error:
the invalid field’s name
the error-reference, see
cerberus.errorsarbitrary, supplemental information about the error
A
ValidationErrorinstance will be created and added to_errors.
- _errors¶
The list of errors that were encountered since the last document processing was invoked. Type:
ErrorList
- _get_child_validator(document_crumb=None, schema_crumb=None, **kwargs)¶
Creates a new instance of Validator-(sub-)class. All initial parameters of the parent are passed to the initialization, unless a parameter is given as an explicit keyword-parameter.
- Parameters:
document_crumb (
tupleor hashable) – Extends thedocument_pathof the child-validator.schema_crumb (
tupleor hashable) – Extends theschema_pathof the child-validator.kwargs (
dict) – Overriding keyword-arguments for initialization.
- Returns:
an instance of
self.__class__
- _lookup_field(path)¶
Searches for a field as defined by path. This method is used by the
dependencyevaluation logic.- Parameters:
path (
str) – Path elements are separated by a.. A leading^indicates that the path relates to the document root, otherwise it relates to the currently evaluated document, which is possibly a subdocument. The sequence^^at the start will be interpreted as a literal^.- Returns:
Either the found field name and its value or
Nonefor both.- Return type:
A two-value
tuple.
- _remaining_rules¶
Keeps track of the rules that are next in line to be evaluated during the validation of a field. Type:
list
- _valid_schemas = {}¶
A
setof hashes derived from validation schemas that are legit for a particularValidatorclass.
- property allow_unknown¶
If
Trueunknown fields that are not defined in the schema will be ignored. If a mapping with a validation schema is given, any undefined field will be validated against its rules. Also see Allowing the Unknown. Type:boolor any mapping
- classmethod clear_caches()¶
Purge the cache of known valid schemas.
- document_error_tree¶
A tree representiation of encountered errors following the structure of the document. Type:
DocumentErrorTree
- error_handler¶
The error handler used to format
errorsand process submitted errors with_error(). Type:BaseErrorHandler
- property errors¶
The errors of the last processing formatted by the handler that is bound to
error_handler.
- property is_child¶
Truefor child-validators obtained with_get_child_validator(). Type:bool
- mandatory_validations = ('nullable',)¶
Rules that are evaluated on any field, regardless whether defined in the schema or not. Type:
tuple
- normalized(document, schema=None, always_return_document=False)¶
Returns the document normalized according to the specified rules of a schema.
- Parameters:
- Returns:
A normalized copy of the provided mapping or
Noneif an error occurred during normalization.
- priority_validations = ('nullable', 'readonly', 'type', 'empty')¶
Rules that will be processed in that order before any other. Type:
tuple
- property purge_unknown¶
If
True, unknown fields will be deleted from the document unless a validation is called with disabled normalization. Also see Purging Unknown Fields. Type:bool
- recent_error¶
The last individual error that was submitted. Type:
ValidationError
- property require_all¶
If
Trueknown fields that are defined in the schema will be required. Type:bool
- property root_allow_unknown¶
The
allow_unknownattribute of the first level ancestor of a child validator.
- property root_require_all¶
The
require_allattribute of the first level ancestor of a child validator.
- property rules_set_registry¶
The registry that holds referenced rules sets. Type:
Registry
- property schema¶
The validation schema of a validator. When a schema is passed to a method, it replaces this attribute. Type: any mapping or
None
- schema_error_tree¶
A tree representiation of encountered errors following the structure of the schema. Type:
SchemaErrorTree
- property schema_registry¶
The registry that holds referenced schemas. Type:
Registry
- types_mapping = {'binary': ('binary', (<class 'bytes'>, <class 'bytearray'>), ()), 'boolean': ('boolean', (<class 'bool'>,), ()), 'container': ('container', (<class 'collections.abc.Container'>,), (<class 'str'>,)), 'date': ('date', (<class 'datetime.date'>,), ()), 'datetime': ('datetime', (<class 'datetime.datetime'>,), ()), 'dict': ('dict', (<class 'collections.abc.Mapping'>,), ()), 'float': ('float', (<class 'float'>, (<class 'int'>,)), ()), 'integer': ('integer', ((<class 'int'>,),), ()), 'list': ('list', (<class 'collections.abc.Sequence'>,), (<class 'str'>,)), 'number': ('number', ((<class 'int'>,), <class 'float'>), (<class 'bool'>,)), 'set': ('set', (<class 'set'>,), ()), 'string': ('string', (<class 'str'>,), ())}¶
This mapping holds all available constraints for the type rule and their assigned
TypeDefinition.
- validate(document, schema=None, update=False, normalize=True)¶
Normalizes and validates a mapping against a validation-schema of defined rules.
- Parameters:
document (any mapping) – The document to normalize.
schema (any mapping) – The validation schema. Defaults to
None. If not provided here, the schema must have been provided at class instantiation.update (
bool) – IfTrue, required fields won’t be checked.normalize (
bool) – IfTrue, normalize the document before validation.
- Returns:
Trueif validation succeeds, otherwiseFalse. Check theerrors()property for a list of processing errors.- Return type:
- validated(*args, **kwargs)¶
Wrapper around
validate()that returns the normalized and validated document orNoneif validation failed.
Rules Set & Schema Registry¶
- class cerberus.schema.Registry(definitions={})¶
A registry to store and retrieve schemas and parts of it by a name that can be used in validation schemas.
- Parameters:
definitions (any mapping) – Optional, initial definitions.
- add(name, definition)¶
Register a definition to the registry. Existing definitions are replaced silently.
- clear()¶
Purge all definitions in the registry.
- extend(definitions)¶
Add several definitions at once. Existing definitions are replaced silently.
- get(name, default=None)¶
Retrieve a definition from the registry.
- Parameters:
name (
str) – The reference that points to the definition.default – Return value if the reference isn’t registered.
- remove(*names)¶
Unregister definitions from the registry.
- Parameters:
names – The names of the definitions that are to be unregistered.
Type Definitions¶
- class cerberus.TypeDefinition(name, included_types, excluded_types)¶
This class is used to define types that can be used as value in the
types_mappingproperty. Thenameshould be descriptive and match the key it is going to be assigned to. A value that is validated against such definition must be an instance of any of the types contained inincluded_typesand must not match any of the types contained inexcluded_types.
Error Handlers¶
- class cerberus.errors.BaseErrorHandler(*args, **kwargs)¶
Base class for all error handlers. Subclasses are identified as error-handlers with an instance-test.
- __call__(errors)¶
Returns errors in a handler-specific format.
- Parameters:
errors (iterable of
ValidationErrorinstances or aValidatorinstance) – An object containing the errors.
- __init__(*args, **kwargs)¶
Optionally initialize a new instance.
- __iter__()¶
Be a superhero and implement an iterator over errors.
- __weakref__¶
list of weak references to the object
- add(error)¶
Add an error to the errors’ container object of a handler.
- Parameters:
error (
ValidationError) – The error to add.
- emit(error)¶
Optionally emits an error in the handler’s format to a stream. Or light a LED, or even shut down a power plant.
- Parameters:
error (
ValidationError) – The error to emit.
- end(validator)¶
Gets called when a validation ends.
- Parameters:
validator (
Validator) – The calling validator.
- extend(errors)¶
Adds all errors to the handler’s container object.
- Parameters:
errors (iterable of
ValidationErrorinstances) – The errors to add.
Python Error Representations¶
- class cerberus.errors.ErrorDefinition(code, rule)¶
This class is used to define possible errors. Each distinguishable error is defined by a unique error
codeas integer and therulethat can cause it as string. The instances’ names do not contain a common prefix as they are supposed to be referenced within the module namespace, e.g.errors.CUSTOM.
- class cerberus.errors.ValidationError(document_path, schema_path, code, rule, constraint, value, info)¶
A simple class to store and query basic error information.
- property child_errors¶
A list that contains the individual errors of a bulk validation error.
- constraint¶
The constraint that failed.
- property definitions_errors¶
Dictionary with errors of an *of-rule mapped to the index of the definition it occurred in. Returns
Noneif not applicable.
- property is_group_error¶
Truefor errors of bulk validations.
- property is_logic_error¶
Truefor validation errors against different schemas with *of-rules.
- property is_normalization_error¶
Truefor normalization errors.
- rule¶
The rule that failed. Type: string
- value¶
The value that failed.
Error Codes¶
Its code attribute uniquely identifies an
ErrorDefinition that is used a concrete error’s
code.
Some codes are actually reserved to mark a shared property of different errors.
These are useful as bitmasks while processing errors. This is the list of the
reserved codes:
|
|
96 |
An error that occurred during normalization. |
|
|
128 |
An error that contains child errors. |
|
|
144 |
An error that was emitted by one of the *of-rules. |
None of these bits in the upper nibble must be used to enumerate error definitions, but only to mark one with the associated property.
Important
Users are advised to set bit 8 for self-defined errors. So the code
0001 0000 0001 / 0x101 would the first in a domain-specific set of
error definitions.
This is a list of all error defintions that are shipped with the
errors module:
Code (dec.) |
Code (hex.) |
Name |
Rule |
|---|---|---|---|
0 |
0x0 |
CUSTOM |
None |
2 |
0x2 |
REQUIRED_FIELD |
required |
3 |
0x3 |
UNKNOWN_FIELD |
None |
4 |
0x4 |
DEPENDENCIES_FIELD |
dependencies |
5 |
0x5 |
DEPENDENCIES_FIELD_VALUE |
dependencies |
6 |
0x6 |
EXCLUDES_FIELD |
excludes |
34 |
0x22 |
EMPTY_NOT_ALLOWED |
empty |
35 |
0x23 |
NOT_NULLABLE |
nullable |
36 |
0x24 |
BAD_TYPE |
type |
37 |
0x25 |
BAD_TYPE_FOR_SCHEMA |
schema |
38 |
0x26 |
ITEMS_LENGTH |
items |
39 |
0x27 |
MIN_LENGTH |
minlength |
40 |
0x28 |
MAX_LENGTH |
maxlength |
65 |
0x41 |
REGEX_MISMATCH |
regex |
66 |
0x42 |
MIN_VALUE |
min |
67 |
0x43 |
MAX_VALUE |
max |
68 |
0x44 |
UNALLOWED_VALUE |
allowed |
69 |
0x45 |
UNALLOWED_VALUES |
allowed |
70 |
0x46 |
FORBIDDEN_VALUE |
forbidden |
71 |
0x47 |
FORBIDDEN_VALUES |
forbidden |
72 |
0x48 |
MISSING_MEMBERS |
contains |
96 |
0x60 |
NORMALIZATION |
None |
97 |
0x61 |
COERCION_FAILED |
coerce |
98 |
0x62 |
RENAMING_FAILED |
rename_handler |
99 |
0x63 |
READONLY_FIELD |
readonly |
100 |
0x64 |
SETTING_DEFAULT_FAILED |
default_setter |
128 |
0x80 |
ERROR_GROUP |
None |
129 |
0x81 |
MAPPING_SCHEMA |
schema |
130 |
0x82 |
SEQUENCE_SCHEMA |
schema |
131 |
0x83 |
KEYSRULES |
keysrules |
131 |
0x83 |
KEYSCHEMA |
keysrules |
132 |
0x84 |
VALUESRULES |
valuesrules |
132 |
0x84 |
VALUESCHEMA |
valuesrules |
143 |
0x8f |
BAD_ITEMS |
items |
144 |
0x90 |
LOGICAL |
None |
145 |
0x91 |
NONEOF |
noneof |
146 |
0x92 |
ONEOF |
oneof |
147 |
0x93 |
ANYOF |
anyof |
148 |
0x94 |
ALLOF |
allof |
Error Containers¶
- class cerberus.errors.ErrorList(iterable=(), /)¶
A list for
ValidationErrorinstances that can be queried with theinkeyword for a particularErrorDefinition.
- class cerberus.errors.ErrorTree(errors=())¶
Base class for
DocumentErrorTreeandSchemaErrorTree.- add(error)¶
Add an error to the tree.
- Parameters:
error –
ValidationError
- fetch_errors_from(path)¶
Returns all errors for a particular path.
- class cerberus.errors.DocumentErrorTree(errors=())¶
Implements a dict-like class to query errors by indexes following the structure of a validated document.
- class cerberus.errors.SchemaErrorTree(errors=())¶
Implements a dict-like class to query errors by indexes following the structure of the used schema.
Exceptions¶
- exception cerberus.SchemaError¶
Raised when the validation schema is missing, has the wrong format or contains errors.
- exception cerberus.DocumentError¶
Raised when the target document is missing or has the wrong format
Utilities¶
- class cerberus.utils.TypeDefinition(name, included_types, excluded_types)¶
This class is used to define types that can be used as value in the
types_mappingproperty. Thenameshould be descriptive and match the key it is going to be assigned to. A value that is validated against such definition must be an instance of any of the types contained inincluded_typesand must not match any of the types contained inexcluded_types.- excluded_types¶
Alias for field number 2
- included_types¶
Alias for field number 1
- name¶
Alias for field number 0
- cerberus.utils.mapping_to_frozenset(mapping)¶
Be aware that this treats any sequence type with the equal members as equal. As it is used to identify equality of schemas, this can be considered okay as definitions are semantically equal regardless the container type.
- class cerberus.utils.readonly_classproperty(fget=None, fset=None, fdel=None, doc=None)¶
Schema Validation Schema¶
Against this schema validation schemas given to a vanilla
Validator will be validated:
{'allof': {'logical': 'allof', 'type': 'list'},
'allow_unknown': {'oneof': [{'type': 'boolean'},
{'check_with': 'bulk_schema',
'type': ['dict', 'string']}]},
'allowed': {'type': 'container'},
'anyof': {'logical': 'anyof', 'type': 'list'},
'check_with': {'oneof': [{'type': 'callable'},
{'schema': {'oneof': [{'type': 'callable'},
{'allowed': (),
'type': 'string'}]},
'type': 'list'},
{'allowed': (), 'type': 'string'}]},
'coerce': {'oneof': [{'type': 'callable'},
{'schema': {'oneof': [{'type': 'callable'},
{'allowed': (),
'type': 'string'}]},
'type': 'list'},
{'allowed': (), 'type': 'string'}]},
'contains': {'empty': False},
'default': {'nullable': True},
'default_setter': {'oneof': [{'type': 'callable'},
{'allowed': (), 'type': 'string'}]},
'dependencies': {'check_with': 'dependencies',
'type': ('dict', 'hashable', 'list')},
'empty': {'type': 'boolean'},
'excludes': {'schema': {'type': 'hashable'},
'type': ('hashable', 'list')},
'forbidden': {'type': 'list'},
'items': {'check_with': 'items', 'type': 'list'},
'keysrules': {'check_with': 'bulk_schema',
'forbidden': ['rename', 'rename_handler'],
'type': ['dict', 'string']},
'max': {'nullable': False},
'maxlength': {'type': 'integer'},
'meta': {},
'min': {'nullable': False},
'minlength': {'type': 'integer'},
'noneof': {'logical': 'noneof', 'type': 'list'},
'nullable': {'type': 'boolean'},
'oneof': {'logical': 'oneof', 'type': 'list'},
'purge_unknown': {'type': 'boolean'},
'readonly': {'type': 'boolean'},
'regex': {'type': 'string'},
'rename': {'type': 'hashable'},
'rename_handler': {'oneof': [{'type': 'callable'},
{'schema': {'oneof': [{'type': 'callable'},
{'allowed': (),
'type': 'string'}]},
'type': 'list'},
{'allowed': (), 'type': 'string'}]},
'require_all': {'type': 'boolean'},
'required': {'type': 'boolean'},
'schema': {'anyof': [{'check_with': 'schema'},
{'check_with': 'bulk_schema'}],
'type': ['dict', 'string']},
'type': {'check_with': 'type', 'type': ['string', 'list']},
'valuesrules': {'check_with': 'bulk_schema',
'forbidden': ['rename', 'rename_handler'],
'type': ['dict', 'string']}}