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_rules
andvalidation_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: - schema (any mapping) – See
schema
. Defaults toNone
. - ignore_none_values (
bool
) – Seeignore_none_values
. Defaults toFalse
. - allow_unknown (
bool
or any mapping) – Seeallow_unknown
. Defaults toFalse
. - purge_unknown (
bool
) – Seepurge_unknown
. Defaults to toFalse
. - error_handler (class or instance based on
BaseErrorHandler
ortuple
) – 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
.
-
_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.errors
- arbitrary, supplemental information about the error
A
ValidationError
instance will be created and added to_errors
.- iterable of
-
_errors
= None¶ 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 (
tuple
or hashable) – Extends thedocument_path
of the child-validator. - schema_crumb (
tuple
or hashable) – Extends theschema_path
of 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
dependency
evaluation 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 None
for both.Return type: A two-value tuple
.
-
_valid_schemas
= set()¶ A
set
of hashed validation schemas that are legit for a particularValidator
class.
-
allow_unknown
¶ If
True
unknown 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:bool
or any mapping
-
clear_caches
()¶ Purge the cache of known valid schemas.
-
document
= None¶ The document that is or was recently processed. Type: any mapping
-
document_error_tree
= None¶ A tree representiation of encountered errors following the structure of the document. Type:
DocumentErrorTree
-
document_path
= None¶ The path within the document to the current sub-document. Type:
tuple
-
error_handler
= None¶ The error handler used to format
errors
and process submitted errors with_error()
. Type:BaseErrorHandler
-
errors
¶ The errors of the last processing formatted by the handler that is bound to
error_handler
.
-
ignore_none_values
¶ Whether to not process
None
-values in a document or not. Type:bool
-
is_child
¶ True
for 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: - 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. - always_return_document (
bool
) – Return the document, even if an error occurred. Defaults to:False
.
Returns: A normalized copy of the provided mapping or
None
if an error occurred during normalization.
-
priority_validations
= ('nullable', 'readonly', 'type')¶ Rules that will be processed in that order before any other and abort validation of a document’s field if return
True
. Type:tuple
-
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
= None¶ The last individual error that was submitted. Type:
ValidationError
-
root_allow_unknown
¶ The
allow_unknown
attribute of the first level ancestor of a child validator.
-
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
= None¶ A tree representiation of encountered errors following the structure of the schema. Type:
SchemaErrorTree
-
schema_path
= None¶ The path within the schema to the current sub-schema. Type:
tuple
-
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: True
if validation succeeds, otherwiseFalse
. Check theerrors()
property for a list of processing errors.Return type: bool
-
validated
(*args, **kwargs)¶ Wrapper around
validate()
that returns the normalized and validated document orNone
if validation failed.
- schema (any mapping) – See
Rules Set & Schema Registry¶
-
class
cerberus.
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.
Parameters: - name (
str
) – The name which can be used as reference in a validation schema. - definition (any mapping) – The definition.
- name (
-
all
()¶ Returns a
dict
with all registered definitions mapped to their name.
-
clear
()¶ Purge all definitions in the registry.
-
extend
(definitions)¶ Add several definitions at once. Existing definitions are replaced silently.
Parameters: definitions (a mapping or an iterable with two-value tuple
s) – The names and definitions.
-
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.
- name (
-
remove
(*names)¶ Unregister definitions from the registry.
Parameters: names – The names of the definitions that are to be unregistered.
-
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 ValidationError
instances or aValidator
instance) – 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 (if defined)
-
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 ValidationError
instances) – The errors to add.
-
-
class
cerberus.errors.
BasicErrorHandler
(tree=None)¶ Models cerberus’ legacy. Returns a
dict
.
Python Error Representations¶
-
class
cerberus.errors.
ValidationError
(document_path, schema_path, code, rule, constraint, value, info)¶ A simple class to store and query basic error information.
-
child_errors
¶ A list that contains the individual errors of a bulk validation error.
-
code
= None¶ The error’s identifier code. Type:
int
-
constraint
= None¶ The constraint that failed.
-
definitions_errors
¶ Dictionary with errors of an *of-rule mapped to the index of the definition it occurred in. Returns
None
if not applicable.
-
document_path
= None¶ The path to the field within the document that caused the error. Type:
tuple
-
field
¶ Field of the contextual mapping, possibly
None
.
-
info
= None¶ May hold additional information about the error. Type:
tuple
-
is_group_error
¶ True
for errors of bulk validations.
-
is_normalization_error
¶ True
for normalization errors.
-
rule
= None¶ The rule that failed. Type: string
-
schema_path
= None¶ The path to the rule within the schema that caused the error. Type:
tuple
-
value
= None¶ The value that failed.
-
Error Codes¶
These errors are used as code
.
-
class
cerberus.errors.
ErrorList
¶ A list for
ValidationError
instances that can be queried with thein
keyword for a particular error code.
-
class
cerberus.errors.
ErrorTree
(errors=[])¶ Base class for
DocumentErrorTree
andSchemaErrorTree
.-
add
(error)¶ Add an error to the tree.
Parameters: error – ValidationError
-
fetch_errors_from
(path)¶ Returns all errors for a particular path.
Parameters: path – tuple
of hashable s.Return type: ErrorList
-
fetch_node_from
(path)¶ Returns a node for a path.
Parameters: path – Tuple of hashable s. Return type: ErrorTreeNode
orNone
-
-
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¶
-
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.
-
cerberus.utils.
validator_factory
(name, mixin=None, class_dict={})¶ - Dynamically create a
Validator
subclass. - Docstrings of mixin-classes will be added to the resulting
class’ one if
__doc__
is not inclass_dict
.
Parameters: - name (
str
) – The name of the new class. - mixin (
tuple
of or a single class) – Class(es) with mixin-methods. - class_dict (
dict
) – Attributes for the new class.
Returns: The created class.
- Dynamically create a