.\" Man page generated from reStructuredText. . .TH "CERBERUS" "1" "Jan 16, 2019" "1.2" "Cerberus" .SH NAME cerberus \- Cerberus Documentation . .nr rst2man-indent-level 0 . .de1 rstReportMargin \\$1 \\n[an-margin] level \\n[rst2man-indent-level] level margin: \\n[rst2man-indent\\n[rst2man-indent-level]] - \\n[rst2man-indent0] \\n[rst2man-indent1] \\n[rst2man-indent2] .. .de1 INDENT .\" .rstReportMargin pre: . RS \\$1 . nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin] . nr rst2man-indent-level +1 .\" .rstReportMargin post: .. .de UNINDENT . RE .\" indent \\n[an-margin] .\" old: \\n[rst2man-indent\\n[rst2man-indent-level]] .nr rst2man-indent-level -1 .\" new: \\n[rst2man-indent\\n[rst2man-indent-level]] .in \\n[rst2man-indent\\n[rst2man-indent-level]]u .. .INDENT 0.0 .INDENT 3.5 \fBCERBERUS\fP, n. The watch\-dog of Hades, whose duty it was to guard the entrance; everybody, sooner or later, had to go there, and nobody wanted to carry off the entrance. \- \fIAmbrose Bierce, The Devil\(aqs Dictionary\fP .UNINDENT .UNINDENT .sp Cerberus provides powerful yet simple and lightweight data validation functionality out of the box and is designed to be easily extensible, allowing for custom validation. It has no dependencies and is thoroughly tested from Python 2.6 up to 3.5, PyPy and PyPy3. .SH AT A GLANCE .sp You define a validation schema and pass it to an instance of the \fBValidator\fP class: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> schema = {\(aqname\(aq: {\(aqtype\(aq: \(aqstring\(aq}} >>> v = Validator(schema) .ft P .fi .UNINDENT .UNINDENT .sp Then you simply invoke the \fBvalidate()\fP to validate a dictionary against the schema. If validation succeeds, \fBTrue\fP is returned: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> document = {\(aqname\(aq: \(aqjohn doe\(aq} >>> v.validate(document) True .ft P .fi .UNINDENT .UNINDENT .SH FUNDING CERBERUS .sp Cerberus is a collaboratively funded project\&. If you run a business and are using Cerberus in a revenue\-generating product, it would make business sense to sponsor its development: it ensures the project that your product relies on stays healthy and actively maintained. .sp Individual users are also welcome to make either a recurring pledge or a one time donation if Cerberus has helped you in your work or personal projects. Every single sign\-up makes a significant impact towards making Cerberus possible. .sp To join the backer ranks, check out \fI\%Cerberus campaign on Patreon\fP\&. .SH TABLE OF CONTENTS .SS Cerberus Installation .sp This part of the documentation covers the installation of Cerberus. The first step to using any software package is getting it properly installed. .SS Stable Version .sp Cerberus is on \fI\%PyPI\fP so all you need to do is: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ pip install cerberus .ft P .fi .UNINDENT .UNINDENT .SS Development Version .sp Cerberus is actively developed on GitHub, where the code is \fI\%always available\fP\&. If you want to work with the development version, there are two ways: you can either let \fIpip\fP pull in the development version, or you can tell it to operate on a git checkout. Either way, virtualenv is recommended. .sp Get the git checkout in a new virtualenv and run in development mode. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ git clone http://github.com/pyeve/cerberus.git Initialized empty Git repository in ~/dev/cerberus.git/ $ cd cerberus $ virtualenv venv \-\-distribute New python executable in venv/bin/python Installing distribute............done. $ . venv/bin/activate $ python setup.py install \&... Finished processing dependencies for Cerberus .ft P .fi .UNINDENT .UNINDENT .sp This will pull in the dependencies and activate the git head as the current version inside the virtualenv. Then all you have to do is run \fBgit pull origin\fP to update to the latest version. .sp To just get the development version without git, do this instead: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ mkdir cerberus $ cd cerberus $ virtualenv venv \-\-distribute $ . venv/bin/activate New python executable in venv/bin/python Installing distribute............done. $ pip install git+git://github.com/pyeve/cerberus.git \&... Cleaning up... .ft P .fi .UNINDENT .UNINDENT .sp And you\(aqre done! .SS Cerberus Usage .SS Basic Usage .sp You define a validation schema and pass it to an instance of the \fBValidator\fP class: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> schema = {\(aqname\(aq: {\(aqtype\(aq: \(aqstring\(aq}} >>> v = Validator(schema) .ft P .fi .UNINDENT .UNINDENT .sp Then you simply invoke the \fBvalidate()\fP to validate a dictionary against the schema. If validation succeeds, \fBTrue\fP is returned: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> document = {\(aqname\(aq: \(aqjohn doe\(aq} >>> v.validate(document) True .ft P .fi .UNINDENT .UNINDENT .sp Alternatively, you can pass both the dictionary and the schema to the \fBvalidate()\fP method: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> v = Validator() >>> v.validate(document, schema) True .ft P .fi .UNINDENT .UNINDENT .sp Which can be handy if your schema is changing through the life of the instance. .sp Details about validation schemas are covered in schemas\&. See validation\-rules and normalization\-rules for an extensive documentation of all supported rules. .sp Unlike other validation tools, Cerberus will not halt and raise an exception on the first validation issue. The whole document will always be processed, and \fBFalse\fP will be returned if validation failed. You can then access the \fBerrors\fP property to obtain a list of issues. See Errors & Error Handling for different output options. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> schema = {\(aqname\(aq: {\(aqtype\(aq: \(aqstring\(aq}, \(aqage\(aq: {\(aqtype\(aq: \(aqinteger\(aq, \(aqmin\(aq: 10}} >>> document = {\(aqname\(aq: \(aqLittle Joe\(aq, \(aqage\(aq: 5} >>> v.validate(document, schema) False >>> v.errors {\(aqage\(aq: [\(aqmin value is 10\(aq]} .ft P .fi .UNINDENT .UNINDENT .sp A \fBDocumentError\fP is raised when the document is not a mapping. .sp The Validator class and its instances are callable, allowing for the following shorthand syntax: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> document = {\(aqname\(aq: \(aqjohn doe\(aq} >>> v(document) True .ft P .fi .UNINDENT .UNINDENT .sp New in version 0.4.1. .SS Allowing the Unknown .sp By default only keys defined in the schema are allowed: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> schema = {\(aqname\(aq: {\(aqtype\(aq: \(aqstring\(aq, \(aqmaxlength\(aq: 10}} >>> v.validate({\(aqname\(aq: \(aqjohn\(aq, \(aqsex\(aq: \(aqM\(aq}, schema) False >>> v.errors {\(aqsex\(aq: [\(aqunknown field\(aq]} .ft P .fi .UNINDENT .UNINDENT .sp However, you can allow unknown document keys pairs by either setting \fBallow_unknown\fP to \fBTrue\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> v.schema = {} >>> v.allow_unknown = True >>> v.validate({\(aqname\(aq: \(aqjohn\(aq, \(aqsex\(aq: \(aqM\(aq}) True .ft P .fi .UNINDENT .UNINDENT .sp Or you can set \fBallow_unknown\fP to a validation schema, in which case unknown fields will be validated against it: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> v.schema = {} >>> v.allow_unknown = {\(aqtype\(aq: \(aqstring\(aq} >>> v.validate({\(aqan_unknown_field\(aq: \(aqjohn\(aq}) True >>> v.validate({\(aqan_unknown_field\(aq: 1}) False >>> v.errors {\(aqan_unknown_field\(aq: [\(aqmust be of string type\(aq]} .ft P .fi .UNINDENT .UNINDENT .sp \fBallow_unknown\fP can also be set at initialization: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> v = Validator({}, allow_unknown=True) >>> v.validate({\(aqname\(aq: \(aqjohn\(aq, \(aqsex\(aq: \(aqM\(aq}) True >>> v.allow_unknown = False >>> v.validate({\(aqname\(aq: \(aqjohn\(aq, \(aqsex\(aq: \(aqM\(aq}) False .ft P .fi .UNINDENT .UNINDENT .sp \fBallow_unknown\fP can also be set as rule to configure a validator for a nested mapping that is checked against the schema rule: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> v = Validator() >>> v.allow_unknown False >>> schema = { \&... \(aqname\(aq: {\(aqtype\(aq: \(aqstring\(aq}, \&... \(aqa_dict\(aq: { \&... \(aqtype\(aq: \(aqdict\(aq, \&... \(aqallow_unknown\(aq: True, # this overrides the behaviour for \&... \(aqschema\(aq: { # the validation of this definition \&... \(aqaddress\(aq: {\(aqtype\(aq: \(aqstring\(aq} \&... } \&... } \&... } >>> v.validate({\(aqname\(aq: \(aqjohn\(aq, \&... \(aqa_dict\(aq: {\(aqan_unknown_field\(aq: \(aqis allowed\(aq}}, \&... schema) True >>> # this fails as allow_unknown is still False for the parent document. >>> v.validate({\(aqname\(aq: \(aqjohn\(aq, \&... \(aqan_unknown_field\(aq: \(aqis not allowed\(aq, \&... \(aqa_dict\(aq:{\(aqan_unknown_field\(aq: \(aqis allowed\(aq}}, \&... schema) False >>> v.errors {\(aqan_unknown_field\(aq: [\(aqunknown field\(aq]} .ft P .fi .UNINDENT .UNINDENT .sp Changed in version 0.9: \fBallow_unknown\fP can also be set for nested dict fields. .sp Changed in version 0.8: \fBallow_unknown\fP can also be set to a validation schema. .SS Fetching Processed Documents .sp The normalization and coercion are performed on the copy of the original document and the result document is available via \fBdocument\fP\-property. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> v.schema = {\(aqamount\(aq: {\(aqtype\(aq: \(aqinteger\(aq, \(aqcoerce\(aq: int}} >>> v.validate({\(aqamount\(aq: \(aq1\(aq}) True >>> v.document {\(aqamount\(aq: 1} .ft P .fi .UNINDENT .UNINDENT .sp Beside the \fBdocument\fP\-property a \fBValidator\fP\-instance has shorthand methods to process a document and fetch its processed result. .SS \fIvalidated\fP Method .sp There\(aqs a wrapper\-method \fBvalidated()\fP that returns the validated document. If the document didn\(aqt validate \fI\%None\fP is returned, unless you call the method with the keyword argument \fBalways_return_document\fP set to \fBTrue\fP\&. It can be useful for flows like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C v = Validator(schema) valid_documents = [x for x in [v.validated(y) for y in documents] if x is not None] .ft P .fi .UNINDENT .UNINDENT .sp If a coercion callable or method raises an exception then the exception will be caught and the validation with fail. .sp New in version 0.9. .SS \fInormalized\fP Method .sp Similarly, the \fBnormalized()\fP method returns a normalized copy of a document without validating it: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> schema = {\(aqamount\(aq: {\(aqcoerce\(aq: int}} >>> document = {\(aqmodel\(aq: \(aqconsumerism\(aq, \(aqamount\(aq: \(aq1\(aq} >>> normalized_document = v.normalized(document, schema) >>> type(normalized_document[\(aqamount\(aq]) .ft P .fi .UNINDENT .UNINDENT .sp New in version 1.0. .SS Warnings .sp Warnings, such as about deprecations or likely causes of trouble, are issued through the Python standard library\(aqs \fI\%warnings\fP module. The logging module can be configured to catch these \fI\%logging.captureWarnings()\fP\&. .SS Validation Schemas .sp A validation schema is a \fI\%mapping\fP, usually a \fI\%dict\fP\&. Schema keys are the keys allowed in the target dictionary. Schema values express the rules that must be matched by the corresponding target values. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C schema = {\(aqname\(aq: {\(aqtype\(aq: \(aqstring\(aq, \(aqmaxlength\(aq: 10}} .ft P .fi .UNINDENT .UNINDENT .sp In the example above we define a target dictionary with only one key, \fBname\fP, which is expected to be a string not longer than 10 characters. Something like \fB{\(aqname\(aq: \(aqjohn doe\(aq}\fP would validate, while something like \fB{\(aqname\(aq: \(aqa very long string\(aq}\fP or \fB{\(aqname\(aq: 99}\fP would not. .sp By default all keys in a document are optional unless the required\-rule is set for a key. .SS Registries .sp There are two default registries in the cerberus module namespace where you can store definitions for schemas and rules sets which then can be referenced in a validation schema. You can furthermore instantiate more \fBRegistry\fP objects and bind them to the \fBrules_set_registry\fP or \fBschema_registry\fP of a validator. You may also set these as keyword\-arguments upon intitialization. .sp Using registries is particulary interesting if .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 schemas shall include references to themselves, vulgo: schema recursion .IP \(bu 2 schemas contain a lot of reused parts and are supposed to be \fI\%serialized\fP .UNINDENT .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> from cerberus import schema_registry >>> schema_registry.add(\(aqnon\-system user\(aq, \&... {\(aquid\(aq: {\(aqmin\(aq: 1000, \(aqmax\(aq: 0xffff}}) >>> schema = {\(aqsender\(aq: {\(aqschema\(aq: \(aqnon\-system user\(aq, \&... \(aqallow_unknown\(aq: True}, \&... \(aqreceiver\(aq: {\(aqschema\(aq: \(aqnon\-system user\(aq, \&... \(aqallow_unknown\(aq: True}} .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> from cerberus import rules_set_registry >>> rules_set_registry.extend(((\(aqboolean\(aq, {\(aqtype\(aq: \(aqboolean\(aq}), \&... (\(aqbooleans\(aq, {\(aqvalueschema\(aq: \(aqboolean\(aq}))) >>> schema = {\(aqfoo\(aq: \(aqbooleans\(aq} .ft P .fi .UNINDENT .UNINDENT .SS Validation .sp Validation schemas themselves are validated when passed to the validator or a new set of rules is set for a document\(aqs field. A \fBSchemaError\fP is raised when an invalid validation schema is encountered. See schema\-validation\-schema for a reference. .sp However, be aware that no validation can be triggered for all changes below that level or when a used definition in a registry changes. You could therefore trigger a validation and catch the exception: .sp .nf .ft C >>> v = Validator({\(aqfoo\(aq: {\(aqallowed\(aq: []}}) >>> v.schema[\(aqfoo\(aq] = {\(aqallowed\(aq: \(aqstrings are no valid constraint for allowed\(aq} Traceback (most recent call last): File "", line 1, in File "cerberus/schema.py", line 99, in __setitem__ self.validate({key: value}) File "cerberus/schema.py", line 126, in validate self._validate(schema) File "cerberus/schema.py", line 141, in _validate raise SchemaError(self.schema_validator.errors) SchemaError: {\(aqfoo\(aq: {\(aqallowed\(aq: \(aqmust be of list type\(aq}} >>> v.schema[\(aqfoo\(aq][\(aqallowed\(aq] = \(aqstrings are no valid constraint for allowed\(aq >>> v.schema.validate() Traceback (most recent call last): File "", line 1, in File "cerberus/schema.py", line 126, in validate self._validate(schema) File "cerberus/schema.py", line 141, in _validate raise SchemaError(self.schema_validator.errors) SchemaError: {\(aqfoo\(aq: {\(aqallowed\(aq: \(aqmust be of list type\(aq}} .ft P .fi .SS Serialization .sp Cerberus schemas are built with vanilla Python types: \fBdict\fP, \fBlist\fP, \fBstring\fP, etc. Even user\-defined validation rules are invoked in the schema by name as a string. A useful side effect of this design is that schemas can be defined in a number of ways, for example with \fI\%PyYAML\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> import yaml >>> schema_text = \(aq\(aq\(aq \&... name: \&... type: string \&... age: \&... type: integer \&... min: 10 \&... \(aq\(aq\(aq >>> schema = yaml.load(schema_text) >>> document = {\(aqname\(aq: \(aqLittle Joe\(aq, \(aqage\(aq: 5} >>> v.validate(document, schema) False >>> v.errors {\(aqage\(aq: [\(aqmin value is 10\(aq]} .ft P .fi .UNINDENT .UNINDENT .sp You don\(aqt have to use YAML of course, you can use your favorite serializer. \fI\%json\fP for example. As long as there is a decoder that can produce a nested \fBdict\fP, you can use it to define a schema. .sp For populating and dumping one of the registries, use \fBextend()\fP and \fBall()\fP\&. .SS Validation Rules .SS allow_unknown .sp This can be used in conjunction with the \fI\%schema\fP rule when validating a mapping in order to set the \fBallow_unknown\fP property of the validator for the subdocument. This rule has precedence over \fBpurge_unknown\fP (see purging\-unknown\-fields). For a full elaboration refer to this paragraph\&. .SS allowed .sp If the target value is an \fI\%iterable\fP, all its members must be in the list of allowed values. Other types of target values will validate if the value is in that list. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> v.schema = {\(aqrole\(aq: {\(aqtype\(aq: \(aqlist\(aq, \(aqallowed\(aq: [\(aqagent\(aq, \(aqclient\(aq, \(aqsupplier\(aq]}} >>> v.validate({\(aqrole\(aq: [\(aqagent\(aq, \(aqsupplier\(aq]}) True >>> v.validate({\(aqrole\(aq: [\(aqintern\(aq]}) False >>> v.errors {\(aqrole\(aq: ["unallowed values [\(aqintern\(aq]"]} >>> v.schema = {\(aqrole\(aq: {\(aqtype\(aq: \(aqstring\(aq, \(aqallowed\(aq: [\(aqagent\(aq, \(aqclient\(aq, \(aqsupplier\(aq]}} >>> v.validate({\(aqrole\(aq: \(aqsupplier\(aq}) True >>> v.validate({\(aqrole\(aq: \(aqintern\(aq}) False >>> v.errors {\(aqrole\(aq: [\(aqunallowed value intern\(aq]} >>> v.schema = {\(aqa_restricted_integer\(aq: {\(aqtype\(aq: \(aqinteger\(aq, \(aqallowed\(aq: [\-1, 0, 1]}} >>> v.validate({\(aqa_restricted_integer\(aq: \-1}) True >>> v.validate({\(aqa_restricted_integer\(aq: 2}) False >>> v.errors {\(aqa_restricted_integer\(aq: [\(aqunallowed value 2\(aq]} .ft P .fi .UNINDENT .UNINDENT .sp Changed in version 0.5.1: Added support for the \fBint\fP type. .SS allof .sp Validates if \fIall\fP of the provided constraints validates the field. See \fI\%*of\-rules\fP for details. .sp New in version 0.9. .SS anyof .sp Validates if \fIany\fP of the provided constraints validates the field. See \fI\%*of\-rules\fP for details. .sp New in version 0.9. .SS dependencies .sp This rule allows to define either a single field name, a sequence of field names or a \fI\%mapping\fP of field names and a sequence of allowed values as required in the document if the field defined upon is present in the document. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> schema = {\(aqfield1\(aq: {\(aqrequired\(aq: False}, \(aqfield2\(aq: {\(aqrequired\(aq: False, \(aqdependencies\(aq: \(aqfield1\(aq}} >>> document = {\(aqfield1\(aq: 7} >>> v.validate(document, schema) True >>> document = {\(aqfield2\(aq: 7} >>> v.validate(document, schema) False >>> v.errors {\(aqfield2\(aq: ["field \(aqfield1\(aq is required"]} .ft P .fi .UNINDENT .UNINDENT .sp When multiple field names are defined as dependencies, all of these must be present in order for the target field to be validated. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> schema = {\(aqfield1\(aq: {\(aqrequired\(aq: False}, \(aqfield2\(aq: {\(aqrequired\(aq: False}, \&... \(aqfield3\(aq: {\(aqrequired\(aq: False, \(aqdependencies\(aq: [\(aqfield1\(aq, \(aqfield2\(aq]}} >>> document = {\(aqfield1\(aq: 7, \(aqfield2\(aq: 11, \(aqfield3\(aq: 13} >>> v.validate(document, schema) True >>> document = {\(aqfield2\(aq: 11, \(aqfield3\(aq: 13} >>> v.validate(document, schema) False >>> v.errors {\(aqfield3\(aq: ["field \(aqfield1\(aq is required"]} .ft P .fi .UNINDENT .UNINDENT .sp When a mapping is provided, not only all dependencies must be present, but also any of their allowed values must be matched. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> schema = {\(aqfield1\(aq: {\(aqrequired\(aq: False}, \&... \(aqfield2\(aq: {\(aqrequired\(aq: True, \(aqdependencies\(aq: {\(aqfield1\(aq: [\(aqone\(aq, \(aqtwo\(aq]}}} >>> document = {\(aqfield1\(aq: \(aqone\(aq, \(aqfield2\(aq: 7} >>> v.validate(document, schema) True >>> document = {\(aqfield1\(aq: \(aqthree\(aq, \(aqfield2\(aq: 7} >>> v.validate(document, schema) False >>> v.errors {\(aqfield2\(aq: ["depends on these values: {\(aqfield1\(aq: [\(aqone\(aq, \(aqtwo\(aq]}"]} >>> # same as using a dependencies list >>> document = {\(aqfield2\(aq: 7} >>> v.validate(document, schema) False >>> v.errors {\(aqfield2\(aq: ["depends on these values: {\(aqfield1\(aq: [\(aqone\(aq, \(aqtwo\(aq]}"]} >>> # one can also pass a single dependency value >>> schema = {\(aqfield1\(aq: {\(aqrequired\(aq: False}, \(aqfield2\(aq: {\(aqdependencies\(aq: {\(aqfield1\(aq: \(aqone\(aq}}} >>> document = {\(aqfield1\(aq: \(aqone\(aq, \(aqfield2\(aq: 7} >>> v.validate(document, schema) True >>> document = {\(aqfield1\(aq: \(aqtwo\(aq, \(aqfield2\(aq: 7} >>> v.validate(document, schema) False >>> v.errors {\(aqfield2\(aq: ["depends on these values: {\(aqfield1\(aq: \(aqone\(aq}"]} .ft P .fi .UNINDENT .UNINDENT .sp Declaring dependencies on subdocument fields with dot\-notation is also supported: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> schema = { \&... \(aqtest_field\(aq: {\(aqdependencies\(aq: [\(aqa_dict.foo\(aq, \(aqa_dict.bar\(aq]}, \&... \(aqa_dict\(aq: { \&... \(aqtype\(aq: \(aqdict\(aq, \&... \(aqschema\(aq: { \&... \(aqfoo\(aq: {\(aqtype\(aq: \(aqstring\(aq}, \&... \(aqbar\(aq: {\(aqtype\(aq: \(aqstring\(aq} \&... } \&... } \&... } >>> document = {\(aqtest_field\(aq: \(aqfoobar\(aq, \(aqa_dict\(aq: {\(aqfoo\(aq: \(aqfoo\(aq}} >>> v.validate(document, schema) False >>> v.errors {\(aqtest_field\(aq: ["field \(aqa_dict.bar\(aq is required"]} .ft P .fi .UNINDENT .UNINDENT .sp When a subdocument is processed the lookup for a field in question starts at the level of that document. In order to address the processed document as root level, the declaration has to start with a \fB^\fP\&. An occurance of two initial carets (\fB^^\fP) is interpreted as a literal, single \fB^\fP with no special meaning. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> schema = { \&... \(aqtest_field\(aq: {}, \&... \(aqa_dict\(aq: { \&... \(aqtype\(aq: \(aqdict\(aq, \&... \(aqschema\(aq: { \&... \(aqfoo\(aq: {\(aqtype\(aq: \(aqstring\(aq}, \&... \(aqbar\(aq: {\(aqtype\(aq: \(aqstring\(aq, \(aqdependencies\(aq: \(aq^test_field\(aq} \&... } \&... } \&... } >>> document = {\(aqa_dict\(aq: {\(aqbar\(aq: \(aqbar\(aq}} >>> v.validate(document, schema) False >>> v.errors {\(aqa_dict\(aq: [{\(aqbar\(aq: ["field \(aq^test_field\(aq is required"]}]} .ft P .fi .UNINDENT .UNINDENT .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 If you want to extend semantics of the dot\-notation, you can override the \fB_lookup_field()\fP method. .UNINDENT .UNINDENT .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 The evaluation of this rule does not consider any constraints defined with the \fI\%required\fP rule. .UNINDENT .UNINDENT .sp Changed in version 1.0.2: Support for absolute addressing with \fB^\fP\&. .sp Changed in version 0.8.1: Support for sub\-document fields as dependencies. .sp Changed in version 0.8: Support for dependencies as a dictionary. .sp New in version 0.7. .SS empty .sp If constrained with \fBFalse\fP validation of an \fI\%iterable\fP value will fail if it is empty. Per default the emptiness of a field isn\(aqt checked and is therefore allowed when the rule isn\(aqt defined. But defining it with the constraint \fBTrue\fP will skip the possibly defined rules \fBallowed\fP, \fBforbidden\fP, \fBitems\fP, \fBminlength\fP, \fBmaxlength\fP, \fBregex\fP and \fBvalidator\fP for that field when the value is considered empty. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> schema = {\(aqname\(aq: {\(aqtype\(aq: \(aqstring\(aq, \(aqempty\(aq: False}} >>> document = {\(aqname\(aq: \(aq\(aq} >>> v.validate(document, schema) False >>> v.errors {\(aqname\(aq: [\(aqempty values not allowed\(aq]} .ft P .fi .UNINDENT .UNINDENT .sp New in version 0.0.3. .SS excludes .sp You can declare fields to excludes others: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> v = Validator() >>> schema = {\(aqthis_field\(aq: {\(aqtype\(aq: \(aqdict\(aq, \&... \(aqexcludes\(aq: \(aqthat_field\(aq}, \&... \(aqthat_field\(aq: {\(aqtype\(aq: \(aqdict\(aq, \&... \(aqexcludes\(aq: \(aqthis_field\(aq}} >>> v.validate({\(aqthis_field\(aq: {}, \(aqthat_field\(aq: {}}, schema) False >>> v.validate({\(aqthis_field\(aq: {}}, schema) True >>> v.validate({\(aqthat_field\(aq: {}}, schema) True >>> v.validate({}, schema) True .ft P .fi .UNINDENT .UNINDENT .sp You can require both field to build an exclusive \fIor\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> v = Validator() >>> schema = {\(aqthis_field\(aq: {\(aqtype\(aq: \(aqdict\(aq, \&... \(aqexcludes\(aq: \(aqthat_field\(aq, \&... \(aqrequired\(aq: True}, \&... \(aqthat_field\(aq: {\(aqtype\(aq: \(aqdict\(aq, \&... \(aqexcludes\(aq: \(aqthis_field\(aq, \&... \(aqrequired\(aq: True}} >>> v.validate({\(aqthis_field\(aq: {}, \(aqthat_field\(aq: {}}, schema) False >>> v.validate({\(aqthis_field\(aq: {}}, schema) True >>> v.validate({\(aqthat_field\(aq: {}}, schema) True >>> v.validate({}, schema) False .ft P .fi .UNINDENT .UNINDENT .sp You can also pass multiples fields to exclude in a list : .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> schema = {\(aqthis_field\(aq: {\(aqtype\(aq: \(aqdict\(aq, \&... \(aqexcludes\(aq: [\(aqthat_field\(aq, \(aqbazo_field\(aq]}, \&... \(aqthat_field\(aq: {\(aqtype\(aq: \(aqdict\(aq, \&... \(aqexcludes\(aq: \(aqthis_field\(aq}, \&... \(aqbazo_field\(aq: {\(aqtype\(aq: \(aqdict\(aq}} >>> v.validate({\(aqthis_field\(aq: {}, \(aqbazo_field\(aq: {}}, schema) False .ft P .fi .UNINDENT .UNINDENT .SS forbidden .sp Opposite to \fI\%allowed\fP this validates if a value is any but one of the defined values: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> schema = {\(aquser\(aq: {\(aqforbidden\(aq: [\(aqroot\(aq, \(aqadmin\(aq]}} >>> document = {\(aquser\(aq: \(aqroot\(aq} >>> v.validate(document, schema) False .ft P .fi .UNINDENT .UNINDENT .sp New in version 1.0. .SS items .sp Validates the items of any iterable against a sequence of rules that must validate each index\-correspondent item. The items will only be evaluated if the given iterable\(aqs size matches the definition\(aqs. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> schema = {\(aqlist_of_values\(aq: {\(aqtype\(aq: \(aqlist\(aq, \(aqitems\(aq: [{\(aqtype\(aq: \(aqstring\(aq}, {\(aqtype\(aq: \(aqinteger\(aq}]}} >>> document = {\(aqlist_of_values\(aq: [\(aqhello\(aq, 100]} >>> v.validate(document, schema) True >>> document = {\(aqlist_of_values\(aq: [100, \(aqhello\(aq]} >>> v.validate(document, schema) False .ft P .fi .UNINDENT .UNINDENT .sp See \fI\%schema (list)\fP rule for dealing with arbitrary length \fBlist\fP types. .SS keyschema .sp Validation schema for all keys of a \fI\%mapping\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> schema = {\(aqa_dict\(aq: {\(aqtype\(aq: \(aqdict\(aq, \(aqkeyschema\(aq: {\(aqtype\(aq: \(aqstring\(aq, \(aqregex\(aq: \(aq[a\-z]+\(aq}}} >>> document = {\(aqa_dict\(aq: {\(aqkey\(aq: \(aqvalue\(aq}} >>> v.validate(document, schema) True >>> document = {\(aqa_dict\(aq: {\(aqKEY\(aq: \(aqvalue\(aq}} >>> v.validate(document, schema) False .ft P .fi .UNINDENT .UNINDENT .sp New in version 0.9. .sp Changed in version 1.0: Renamed from \fBpropertyschema\fP to \fBkeyschema\fP .SS min, max .sp Minimum and maximum value allowed for any types that implement comparison operators. .sp Changed in version 1.0: Allows any type to be compared. .sp Changed in version 0.7: Added support for \fBfloat\fP and \fBnumber\fP types. .SS minlength, maxlength .sp Minimum and maximum length allowed for iterables. .SS noneof .sp Validates if \fInone\fP of the provided constraints validates the field. See \fI\%*of\-rules\fP for details. .sp New in version 0.9. .SS nullable .sp If \fBTrue\fP the field value is allowed to be \fI\%None\fP\&. The rule will be checked on every field, regardless it\(aqs defined or not. The rule\(aqs constraint defaults \fBFalse\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> v.schema = {\(aqa_nullable_integer\(aq: {\(aqnullable\(aq: True, \(aqtype\(aq: \(aqinteger\(aq}, \(aqan_integer\(aq: {\(aqtype\(aq: \(aqinteger\(aq}} >>> v.validate({\(aqa_nullable_integer\(aq: 3}) True >>> v.validate({\(aqa_nullable_integer\(aq: None}) True >>> v.validate({\(aqan_integer\(aq: 3}) True >>> v.validate({\(aqan_integer\(aq: None}) False >>> v.errors {\(aqan_integer\(aq: [\(aqnull value not allowed\(aq]} .ft P .fi .UNINDENT .UNINDENT .sp Changed in version 0.7: \fBnullable\fP is valid on fields lacking type definition. .sp New in version 0.3.0. .SS *of\-rules .sp These rules allow you to define different sets of rules to validate against. The field will be considered valid if it validates against the set in the list according to the prefixes logics \fBall\fP, \fBany\fP, \fBone\fP or \fBnone\fP\&. .TS center; |l|l|. _ T{ \fBallof\fP T} T{ Validates if \fIall\fP of the provided constraints validates the field. T} _ T{ \fBanyof\fP T} T{ Validates if \fIany\fP of the provided constraints validates the field. T} _ T{ \fBnoneof\fP T} T{ Validates if \fInone\fP of the provided constraints validates the field. T} _ T{ \fBoneof\fP T} T{ Validates if \fIexactly one\fP of the provided constraints applies. T} _ .TE .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 Normalization cannot be used in the rule sets within the constraints of these rules. .UNINDENT .UNINDENT .sp For example, to verify that a field\(aqs value is a number between 0 and 10 or 100 and 110, you could do the following: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> schema = {\(aqprop1\(aq: \&... {\(aqtype\(aq: \(aqnumber\(aq, \&... \(aqanyof\(aq: \&... [{\(aqmin\(aq: 0, \(aqmax\(aq: 10}, {\(aqmin\(aq: 100, \(aqmax\(aq: 110}]}} >>> document = {\(aqprop1\(aq: 5} >>> v.validate(document, schema) True >>> document = {\(aqprop1\(aq: 105} >>> v.validate(document, schema) True >>> document = {\(aqprop1\(aq: 55} >>> v.validate(document, schema) False >>> v.errors {\(aqprop1\(aq: [\(aqno definitions validate\(aq, {\(aqanyof definition 0\(aq: [\(aqmax value is 10\(aq], \(aqanyof definition 1\(aq: [\(aqmin value is 100\(aq]}]} .ft P .fi .UNINDENT .UNINDENT .sp The \fBanyof\fP rule tests each rules set in the list. Hence, the above schema is equivalent to creating two separate schemas: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> schema1 = {\(aqprop1\(aq: {\(aqtype\(aq: \(aqnumber\(aq, \(aqmin\(aq: 0, \(aqmax\(aq: 10}} >>> schema2 = {\(aqprop1\(aq: {\(aqtype\(aq: \(aqnumber\(aq, \(aqmin\(aq: 100, \(aqmax\(aq: 110}} >>> document = {\(aqprop1\(aq: 5} >>> v.validate(document, schema1) or v.validate(document, schema2) True >>> document = {\(aqprop1\(aq: 105} >>> v.validate(document, schema1) or v.validate(document, schema2) True >>> document = {\(aqprop1\(aq: 55} >>> v.validate(document, schema1) or v.validate(document, schema2) False .ft P .fi .UNINDENT .UNINDENT .sp \fBATTENTION:\fP .INDENT 0.0 .INDENT 3.5 Normalization rules cannot be defined within these rule sets. .UNINDENT .UNINDENT .sp New in version 0.9. .SS *of\-rules typesaver .sp You can concatenate any of\-rule with an underscore and another rule with a list of rule\-values to save typing: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C {\(aqfoo\(aq: {\(aqanyof_type\(aq: [\(aqstring\(aq, \(aqinteger\(aq]}} # is equivalent to {\(aqfoo\(aq: {\(aqanyof\(aq: [{\(aqtype\(aq: \(aqstring\(aq}, {\(aqtype\(aq: \(aqinteger\(aq}]}} .ft P .fi .UNINDENT .UNINDENT .sp Thus you can use this to validate a document against several schemas without implementing your own logic: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> schemas = [{\(aqdepartment\(aq: {\(aqrequired\(aq: True, \(aqregex\(aq: \(aq^IT$\(aq}, \(aqphone\(aq: {\(aqnullable\(aq: True}}, \&... {\(aqdepartment\(aq: {\(aqrequired\(aq: True}, \(aqphone\(aq: {\(aqrequired\(aq: True}}] >>> emloyee_vldtr = Validator({\(aqemployee\(aq: {\(aqoneof_schema\(aq: schemas, \(aqtype\(aq: \(aqdict\(aq}}, allow_unknown=True) >>> invalid_employees_phones = [] >>> for employee in employees: \&... if not employee_vldtr.validate(employee): \&... invalid_employees_phones.append(employee) .ft P .fi .UNINDENT .UNINDENT .SS oneof .sp Validates if \fIexactly one\fP of the provided constraints applies. See \fI\%*of\-rules\fP for details. .sp New in version 0.9. .SS readonly .sp If \fBTrue\fP the value is readonly. Validation will fail if this field is present in the target dictionary. This is useful, for example, when receiving a payload which is to be validated before it is sent to the datastore. The field might be provided by the datastore, but should not writable. .sp Changed in version 1.0.2: Can be used in conjunction with \fBdefault\fP and \fBdefault_setter\fP, see default\-values\&. .SS regex .sp Validation will fail if field value does not match the provided regular expression. It is only tested on string values. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> schema = {\(aqemail\(aq: {\(aqtype\(aq: \(aqstring\(aq, \(aqregex\(aq: \(aq^[a\-zA\-Z0\-9_.+\-]+@[a\-zA\-Z0\-9\-]+\e.[a\-zA\-Z0\-9\-.]+$\(aq}} >>> document = {\(aqemail\(aq: \(aqjohn@example.com\(aq} >>> v.validate(document, schema) True >>> document = {\(aqemail\(aq: \(aqjohn_at_example_dot_com\(aq} >>> v.validate(document, schema) False >>> v.errors {\(aqemail\(aq: ["value does not match regex \(aq^[a\-zA\-Z0\-9_.+\-]+@[a\-zA\-Z0\-9\-]+\e\e.[a\-zA\-Z0\-9\-.]+$\(aq"]} .ft P .fi .UNINDENT .UNINDENT .sp For details on regular expression syntax, see the documentation on the standard library\(aqs \fI\%re\fP\-module. Mind that you can set flags as part of the expression, look for \fB(?aiLmsux)\fP in that document. .sp New in version 0.7. .SS required .sp If \fBTrue\fP the field is mandatory. Validation will fail when it is missing, unless \fBvalidate()\fP is called with \fBupdate=True\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> v.schema = {\(aqname\(aq: {\(aqrequired\(aq: True, \(aqtype\(aq: \(aqstring\(aq}, \(aqage\(aq: {\(aqtype\(aq: \(aqinteger\(aq}} >>> document = {\(aqage\(aq: 10} >>> v.validate(document) False >>> v.errors {\(aqname\(aq: [\(aqrequired field\(aq]} >>> v.validate(document, update=True) True .ft P .fi .UNINDENT .UNINDENT .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 String fields with empty values will still be validated, even when \fBrequired\fP is set to \fBTrue\fP\&. If you don\(aqt want to accept empty values, see the \fI\%empty\fP rule. .UNINDENT .UNINDENT .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 The evaluation of this rule does not consider any constraints defined with the \fI\%dependencies\fP rule. .UNINDENT .UNINDENT .sp Changed in version 0.8: Check field dependencies. .SS schema (dict) .sp If a field for which a \fBschema\fP\-rule is defined has a \fImapping\fP as value, that mapping will be validated against the schema that is provided as constraint. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> schema = {\(aqa_dict\(aq: {\(aqtype\(aq: \(aqdict\(aq, \(aqschema\(aq: {\(aqaddress\(aq: {\(aqtype\(aq: \(aqstring\(aq}, \&... \(aqcity\(aq: {\(aqtype\(aq: \(aqstring\(aq, \(aqrequired\(aq: True}}}} >>> document = {\(aqa_dict\(aq: {\(aqaddress\(aq: \(aqmy address\(aq, \(aqcity\(aq: \(aqmy town\(aq}} >>> v.validate(document, schema) True .ft P .fi .UNINDENT .UNINDENT .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 To validate \fIarbitrary keys\fP of a mapping, see \fI\%keyschema\fP, resp. \fI\%valueschema\fP for validating \fIarbitrary values\fP of a mapping. .UNINDENT .UNINDENT .SS schema (list) .sp If \fBschema\fP\-validation encounters an arbritrary sized \fIsequence\fP as value, all items of the sequence will be validated against the rules provided in \fBschema\fP\(aqs constraint. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> schema = {\(aqa_list\(aq: {\(aqtype\(aq: \(aqlist\(aq, \(aqschema\(aq: {\(aqtype\(aq: \(aqinteger\(aq}}} >>> document = {\(aqa_list\(aq: [3, 4, 5]} >>> v.validate(document, schema) True .ft P .fi .UNINDENT .UNINDENT .sp The \fIschema\fP rule on \fBlist\fP types is also the preferred method for defining and validating a list of dictionaries. .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 Using this rule should be accompanied with a \fBtype\fP\-rule explicitly restricting the field to the \fBlist\fP\-type like in the example. Otherwise false results can be expected when a mapping is validated against this rule with constraints for a sequence. .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> schema = {\(aqrows\(aq: {\(aqtype\(aq: \(aqlist\(aq, \&... \(aqschema\(aq: {\(aqtype\(aq: \(aqdict\(aq, \(aqschema\(aq: {\(aqsku\(aq: {\(aqtype\(aq: \(aqstring\(aq}, \&... \(aqprice\(aq: {\(aqtype\(aq: \(aqinteger\(aq}}}}} >>> document = {\(aqrows\(aq: [{\(aqsku\(aq: \(aqKT123\(aq, \(aqprice\(aq: 100}]} >>> v.validate(document, schema) True .ft P .fi .UNINDENT .UNINDENT .sp Changed in version 0.0.3: Schema rule for \fBlist\fP types of arbitrary length .SS type .sp Data type allowed for the key value. Can be one of the following names: .TS center; |l|l|l|. _ T{ Type Name T} T{ Python 2 Type T} T{ Python 3 Type T} _ T{ \fBboolean\fP T} T{ \fI\%bool\fP T} T{ \fI\%bool\fP T} _ T{ \fBbinary\fP T} T{ \fBbytes\fP [1], \fI\%bytearray\fP T} T{ \fI\%bytes\fP, \fI\%bytearray\fP T} _ T{ \fBdate\fP T} T{ \fI\%datetime.date\fP T} T{ \fI\%datetime.date\fP T} _ T{ \fBdatetime\fP T} T{ \fI\%datetime.datetime\fP T} T{ \fI\%datetime.datetime\fP T} _ T{ \fBdict\fP T} T{ \fI\%collections.Mapping\fP T} T{ \fI\%collections.abc.Mapping\fP T} _ T{ \fBfloat\fP T} T{ \fI\%float\fP T} T{ \fI\%float\fP T} _ T{ \fBinteger\fP T} T{ \fI\%int\fP, \fI\%long\fP T} T{ \fI\%int\fP T} _ T{ \fBlist\fP T} T{ \fI\%collections.Sequence\fP, excl. \fBstring\fP T} T{ \fI\%collections.abc.Sequence\fP, excl. \fBstring\fP T} _ T{ \fBnumber\fP T} T{ \fI\%float\fP, \fI\%int\fP, \fI\%long\fP, excl. \fI\%bool\fP T} T{ \fI\%float\fP, \fI\%int\fP, excl. \fI\%bool\fP T} _ T{ \fBset\fP T} T{ \fI\%set\fP T} T{ \fI\%set\fP T} _ T{ \fBstring\fP T} T{ \fI\%basestring()\fP T} T{ \fI\%str\fP T} _ .TE .sp You can extend this list and support custom types\&. .sp A list of types can be used to allow different values: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> v.schema = {\(aqquotes\(aq: {\(aqtype\(aq: [\(aqstring\(aq, \(aqlist\(aq]}} >>> v.validate({\(aqquotes\(aq: \(aqHello world!\(aq}) True >>> v.validate({\(aqquotes\(aq: [\(aqDo not disturb my circles!\(aq, \(aqHeureka!\(aq]}) True .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> v.schema = {\(aqquotes\(aq: {\(aqtype\(aq: [\(aqstring\(aq, \(aqlist\(aq], \(aqschema\(aq: {\(aqtype\(aq: \(aqstring\(aq}}} >>> v.validate({\(aqquotes\(aq: \(aqHello world!\(aq}) True >>> v.validate({\(aqquotes\(aq: [1, \(aqHeureka!\(aq]}) False >>> v.errors {\(aqquotes\(aq: [{0: [\(aqmust be of string type\(aq]}]} .ft P .fi .UNINDENT .UNINDENT .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 While the \fBtype\fP rule is not required to be set at all, it is not encouraged to leave it unset especially when using more complex rules such as \fBschema\fP\&. If you decide you still don\(aqt want to set an explicit type, rules such as \fBschema\fP are only applied to values where the rules can actually be used (such as \fBdict\fP and \fBlist\fP). Also, in the case of \fBschema\fP, cerberus will try to decide if a \fBlist\fP or a \fBdict\fP type rule is more appropriate and infer it depending on what the \fBschema\fP rule looks like. .UNINDENT .UNINDENT .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 Please note that type validation is performed before most others which exist for the same field (only \fI\%nullable\fP and \fI\%readonly\fP are considered beforehand). In the occurrence of a type failure subsequent validation rules on the field will be skipped and validation will continue on other fields. This allows to safely assume that field type is correct when other (standard or custom) rules are invoked. .UNINDENT .UNINDENT .sp Changed in version 1.0: Added the \fBbinary\fP data type. .sp Changed in version 0.9: If a list of types is given, the key value must match \fIany\fP of them. .sp Changed in version 0.7.1: \fBdict\fP and \fBlist\fP typechecking are now performed with the more generic \fBMapping\fP and \fBSequence\fP types from the builtin \fBcollections\fP module. This means that instances of custom types designed to the same interface as the builtin \fBdict\fP and \fBlist\fP types can be validated with Cerberus. We exclude strings when type checking for \fBlist\fP/\fBSequence\fP because it in the validation situation it is almost certain the string was not the intended data type for a sequence. .sp Changed in version 0.7: Added the \fBset\fP data type. .sp Changed in version 0.6: Added the \fBnumber\fP data type. .sp Changed in version 0.4.0: Type validation is always executed first, and blocks other field validation rules on failure. .sp Changed in version 0.3.0: Added the \fBfloat\fP data type. .IP [1] 5 This is actually an alias of \fI\%str\fP in Python 2. .SS validator .sp Validates the value by calling either a function or method. .sp A function must be implemented like this the following prototype: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C def validationname(field, value, error): if value is invalid: error(field, \(aqerror message\(aq) .ft P .fi .UNINDENT .UNINDENT .sp The \fBerror\fP argument points to the calling validator\(aqs \fB_error\fP method. See customize on how to submit errors. .sp Here\(aqs an example that tests whether an integer is odd or not: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C def oddity(field, value, error): if not value & 1: error(field, "Must be an odd number") .ft P .fi .UNINDENT .UNINDENT .sp Then, you can validate a value like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> schema = {\(aqamount\(aq: {\(aqvalidator\(aq: oddity}} >>> v = Validator(schema) >>> v.validate({\(aqamount\(aq: 10}) False >>> v.errors {\(aqamount\(aq: [\(aqMust be an odd number\(aq]} >>> v.validate({\(aqamount\(aq: 9}) True .ft P .fi .UNINDENT .UNINDENT .sp If the rule\(aqs constraint is a string, the \fBValidator\fP instance must have a method with that name prefixed by \fB_validator_\fP\&. See customize for an equivalent to the function\-based example above. .sp The constraint can also be a sequence of these that will be called consecutively. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C schema = {\(aqfield\(aq: {\(aqvalidator\(aq: [oddity, \(aqprime number\(aq]}} .ft P .fi .UNINDENT .UNINDENT .SS valueschema .sp Validation schema for all values of a \fI\%mapping\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> schema = {\(aqnumbers\(aq: {\(aqtype\(aq: \(aqdict\(aq, \(aqvalueschema\(aq: {\(aqtype\(aq: \(aqinteger\(aq, \(aqmin\(aq: 10}}} >>> document = {\(aqnumbers\(aq: {\(aqan integer\(aq: 10, \(aqanother integer\(aq: 100}} >>> v.validate(document, schema) True >>> document = {\(aqnumbers\(aq: {\(aqan integer\(aq: 9}} >>> v.validate(document, schema) False >>> v.errors {\(aqnumbers\(aq: [{\(aqan integer\(aq: [\(aqmin value is 10\(aq]}]} .ft P .fi .UNINDENT .UNINDENT .sp New in version 0.7. .sp Changed in version 0.9: renamed \fBkeyschema\fP to \fBvalueschema\fP .SS Normalization Rules .sp Normalization rules are applied to fields, also in \fBschema\fP for mappings, as well when defined as a bulk operation by \fBschema\fP (for sequences), \fBallow_unknown\fP, \fBkeyschema\fP and \fBvalueschema\fP\&. Normalization rules in definitions for testing variants like with \fBanyof\fP are not processed. .sp The normalizations are applied as given in this document for each level in the mapping, traversing depth\-first. .SS Renaming Of Fields .sp You can define a field to be renamed before any further processing. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> v = Validator({\(aqfoo\(aq: {\(aqrename\(aq: \(aqbar\(aq}}) >>> v.normalized({\(aqfoo\(aq: 0}) {\(aqbar\(aq: 0} .ft P .fi .UNINDENT .UNINDENT .sp To let a callable rename a field or arbitrary fields, you can define a handler for renaming. If the constraint is a string, it points to a custom method\&. If the constraint is an iterable, the value is processed through that chain. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> v = Validator({}, allow_unknown={\(aqrename_handler\(aq: int}) >>> v.normalized({\(aq0\(aq: \(aqfoo\(aq}) {0: \(aqfoo\(aq} .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> even_digits = lambda x: \(aq0\(aq + x if len(x) % 2 else x >>> v = Validator({}, allow_unknown={\(aqrename_handler\(aq: [str, even_digits]}) >>> v.normalized({1: \(aqfoo\(aq}) {\(aq01\(aq: \(aqfoo\(aq} .ft P .fi .UNINDENT .UNINDENT .sp New in version 1.0. .SS Purging Unknown Fields .sp After renaming, unknown fields will be purged if the \fBpurge_unknown\fP property of a \fBValidator\fP instance is \fBTrue\fP; it defaults to \fBFalse\fP\&. You can set the property per keyword\-argument upon initialization or as rule for subdocuments like \fBallow_unknown\fP (see allowing\-the\-unknown). The default is \fBFalse\fP\&. If a subdocument includes an \fBallow_unknown\fP rule then unknown fields will not be purged on that subdocument. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> v = Validator({\(aqfoo\(aq: {\(aqtype\(aq: \(aqstring\(aq}}, purge_unknown=True) >>> v.normalized({\(aqbar\(aq: \(aqfoo\(aq}) {} .ft P .fi .UNINDENT .UNINDENT .sp New in version 1.0. .SS Default Values .sp You can set default values for missing fields in the document by using the \fBdefault\fP rule. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> v.schema = {\(aqamount\(aq: {\(aqtype\(aq: \(aqinteger\(aq}, \(aqkind\(aq: {\(aqtype\(aq: \(aqstring\(aq, \(aqdefault\(aq: \(aqpurchase\(aq}} >>> v.normalized({\(aqamount\(aq: 1}) == {\(aqamount\(aq: 1, \(aqkind\(aq: \(aqpurchase\(aq} True >>> v.normalized({\(aqamount\(aq: 1, \(aqkind\(aq: None}) == {\(aqamount\(aq: 1, \(aqkind\(aq: \(aqpurchase\(aq} True >>> v.normalized({\(aqamount\(aq: 1, \(aqkind\(aq: \(aqother\(aq}) == {\(aqamount\(aq: 1, \(aqkind\(aq: \(aqother\(aq} True .ft P .fi .UNINDENT .UNINDENT .sp You can also define a default setter callable to set the default value dynamically. The callable gets called with the current (sub)document as the only argument. Callables can even depend on one another, but normalizing will fail if there is a unresolvable/circular dependency. If the constraint is a string, it points to a custom method\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> v.schema = {\(aqa\(aq: {\(aqtype\(aq: \(aqinteger\(aq}, \(aqb\(aq: {\(aqtype\(aq: \(aqinteger\(aq, \(aqdefault_setter\(aq: lambda doc: doc[\(aqa\(aq] + 1}} >>> v.normalized({\(aqa\(aq: 1}) == {\(aqa\(aq: 1, \(aqb\(aq: 2} True >>> v.schema = {\(aqa\(aq: {\(aqtype\(aq: \(aqinteger\(aq, \(aqdefault_setter\(aq: lambda doc: doc[\(aqnot_there\(aq]}} >>> v.normalized({}) >>> v.errors {\(aqa\(aq: ["default value for \(aqa\(aq cannot be set: Circular dependencies of default setters."]} .ft P .fi .UNINDENT .UNINDENT .sp You can even use both \fBdefault\fP and readonly on the same field. This will create a field that cannot be assigned a value manually but it will be automatically supplied with a default value by Cerberus. Of course the same applies for \fBdefault_setter\fP\&. .sp Changed in version 1.0.2: Can be used in conjunction with readonly\&. .sp New in version 1.0. .SS Value Coercion .sp Coercion allows you to apply a callable (given as object or the name of a custom coercion method) to a value before the document is validated. The return value of the callable replaces the new value in the document. This can be used to convert values or sanitize data before it is validated. If the constraint is an iterable of callables and names, the value is processed through that chain of coercers. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> v.schema = {\(aqamount\(aq: {\(aqtype\(aq: \(aqinteger\(aq}} >>> v.validate({\(aqamount\(aq: \(aq1\(aq}) False >>> v.schema = {\(aqamount\(aq: {\(aqtype\(aq: \(aqinteger\(aq, \(aqcoerce\(aq: int}} >>> v.validate({\(aqamount\(aq: \(aq1\(aq}) True >>> v.document {\(aqamount\(aq: 1} >>> to_bool = lambda v: v.lower() in (\(aqtrue\(aq, \(aq1\(aq) >>> v.schema = {\(aqflag\(aq: {\(aqtype\(aq: \(aqboolean\(aq, \(aqcoerce\(aq: (str, to_bool)}} >>> v.validate({\(aqflag\(aq: \(aqtrue\(aq}) True >>> v.document {\(aqflag\(aq: True} .ft P .fi .UNINDENT .UNINDENT .sp New in version 0.9. .SS Errors & Error Handling .sp Errors can be evaluated via Python interfaces or be processed to different output formats with error handlers. .SS Error Handlers .sp Error handlers will return different output via the \fBerrors\fP property of a validator after the processing of a document. They base on \fBBaseErrorHandler\fP which defines the mandatory interface. The error handler to be used can be passed as keyword\-argument \fBerror_handler\fP to the initialization of a validator or by setting it\(aqs property with the same name at any time. On initialization either an instance or a class can be provided. To pass keyword\-arguments to the initialization of a class, provide a two\-value tuple with the error handler class and the dictionary containing the arguments. .sp The following handlers are available: .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 \fBBasicErrorHandler\fP: This is the \fBdefault\fP that returns a dictionary. The keys refer to the document\(aqs ones and the values are lists containing error messages. Errors of nested fields are kept in a dictionary as last item of these lists. .UNINDENT .UNINDENT .UNINDENT .SS Python interfaces .sp An error is represented as \fBValidationError\fP that has the following properties: .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 \fBdocument_path\fP: The path within the document. For flat dictionaries this simply is a key\(aqs name in a tuple, for nested ones it\(aqs all traversed key names. Items in sequences are represented by their index. .IP \(bu 2 \fBschema_path\fP: The path within the schema. .IP \(bu 2 \fBcode\fP: The unique identifier for an error. See error\-codes for a list. .IP \(bu 2 \fBrule\fP: The rule that was evaluated when the error occurred. .IP \(bu 2 \fBconstraint\fP: That rule\(aqs constraint. .IP \(bu 2 \fBvalue\fP: The value being validated. .IP \(bu 2 \fBinfo\fP: This tuple contains additional information that were submitted with the error. For most errors this is actually nothing. For bulk validations (e.g. with \fBitems\fP or \fBkeyschema\fP) this property keeps all individual errors. See the implementation of a rule in the source code to figure out its additional logging. .UNINDENT .UNINDENT .UNINDENT .sp You can access the errors per these properties of a \fBValidator\fP instance after a processing of a document: .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 \fB_errors\fP: This \fBErrorsList\fP instance holds all submitted errors. It is not intended to manipulate errors directly via this attribute. You can test if at least one error with a specific error definition is \fBin\fP that list. .IP \(bu 2 \fBdocument_error_tree\fP: A \fBdict\fP\-like object that allows you to query nodes corresponding to your document. The subscript notation on a node allows to fetch either a specific error that matches the given \fBErrorDefinition\fP or a child node with the given key. If there\(aqs no matching error respectively no errors occurred in a node or below, \fI\%None\fP will be returned instead. A node can also be tested with the \fBin\fP operator with either an \fBErrorDefinition\fP or a possible child node\(aqs key. A node\(aqs errors are contained in its \fBerrors\fP property which is also an \fBErrorsList\fP\&. Its members are yielded when iterating over a node. .IP \(bu 2 \fBschema_error_tree\fP: Similarly for the used schema. .UNINDENT .UNINDENT .UNINDENT .sp Changed in version 1.0: Errors are stored as \fBValidationError\fP in a \fBErrorList\fP\&. .SS Examples .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> schema = {\(aqcats\(aq: {\(aqtype\(aq: \(aqinteger\(aq}} >>> document = {\(aqcats\(aq: \(aqtwo\(aq} >>> v.validate(document, schema) False >>> cerberus.errors.BAD_TYPE in v._errors True >>> v.document_error_tree[\(aqcats\(aq].errors == v.schema_error_tree[\(aqcats\(aq][\(aqtype\(aq].errors True >>> cerberus.errors.BAD_TYPE in v.document_error_tree[\(aqcats\(aq] True >>> v.document_error_tree[\(aqcats\(aq][cerberus.errors.BAD_TYPE] \e \&... == v.document_error_tree[\(aqcats\(aq].errors[0] True >>> error = v.document_error_tree[\(aqcats\(aq].errors[0] >>> error.document_path (\(aqcats\(aq,) >>> error.schema_path (\(aqcats\(aq, \(aqtype\(aq) >>> error.rule \(aqtype\(aq >>> error.constraint \(aqinteger\(aq >>> error.value \(aqtwo\(aq .ft P .fi .UNINDENT .UNINDENT .SS Extending Cerberus .sp Though you can use functions in conjunction with the \fBcoerce\fP and the \fBvalidator\fP rules, you can easily extend the \fBValidator\fP class with custom \fIrules\fP, \fItypes\fP, \fIvalidators\fP, \fIcoercers\fP and \fIdefault_setters\fP\&. While the function\-based style is more suitable for special and one\-off uses, a custom class leverages these possibilities: .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 custom rules can be defined with constrains in a schema .IP \(bu 2 extending the available type s .IP \(bu 2 use additional contextual data .IP \(bu 2 schemas are serializable .UNINDENT .UNINDENT .UNINDENT .sp The references in schemas to these custom methods can use space characters instead of underscores, e.g. \fB{\(aqfoo\(aq: {\(aqvalidator\(aq: \(aqis odd\(aq}}\fP is an alias for \fB{\(aqfoo\(aq: {\(aqvalidator\(aq: \(aqis_odd\(aq}}\fP\&. .SS Custom Rules .sp Suppose that in our use case some values can only be expressed as odd integers, therefore we decide to add support for a new \fBisodd\fP rule to our validation schema: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C schema = {\(aqamount\(aq: {\(aqisodd\(aq: True, \(aqtype\(aq: \(aqinteger\(aq}} .ft P .fi .UNINDENT .UNINDENT .sp This is how we would go to implement that: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from cerberus import Validator class MyValidator(Validator): def _validate_isodd(self, isodd, field, value): """ Test the oddity of a value. The rule\(aqs arguments are validated against this schema: {\(aqtype\(aq: \(aqboolean\(aq} """ if isodd and not bool(value & 1): self._error(field, "Must be an odd number") .ft P .fi .UNINDENT .UNINDENT .sp By subclassing Cerberus \fBValidator\fP class and adding the custom \fB_validate_\fP method, we just enhanced Cerberus to suit our needs. The custom rule \fBisodd\fP is now available in our schema and, what really matters, we can use it to validate all odd values: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> v = MyValidator(schema) >>> v.validate({\(aqamount\(aq: 10}) False >>> v.errors {\(aqamount\(aq: [\(aqMust be an odd number\(aq]} >>> v.validate({\(aqamount\(aq: 9}) True .ft P .fi .UNINDENT .UNINDENT .sp As schemas themselves are validated, you can provide constraints as literal Python expression in the docstring of the rule\(aqs implementing method to validate the arguments given in a schema for that rule. Either the docstring contains solely the literal or the literal is placed at the bottom of the docstring preceded by \fBThe rule\(aqs arguments are validated against this schema:\fP See the source of the contributed rules for more examples. .SS Custom Data Types .sp Cerberus supports and validates several standard data types (see type). When building a custom validator you can add and validate your own data types. .sp Additional types can be added on the fly by assigning a \fBTypeDefinition\fP to the designated type name in \fBtypes_mapping\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from decimal import Decimal decimal_type = cerberus.TypeDefinition(\(aqdecimal\(aq, (Decimal,), ()) Validator.types_mapping[\(aqdecimal\(aq] = decimal_type .ft P .fi .UNINDENT .UNINDENT .sp \fBCAUTION:\fP .INDENT 0.0 .INDENT 3.5 As the \fBtypes_mapping\fP property is a mutable type, any change to its items on an instance will affect its class. .UNINDENT .UNINDENT .sp They can also be defined for subclasses of \fBValidator\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from decimal import Decimal decimal_type = cerberus.TypeDefinition(\(aqdecimal\(aq, (Decimal,), ()) class CustomValidator(Validator): types_mapping = Validator.types_mapping.copy() types_mapping[\(aqdecimal\(aq] = decimal_type .ft P .fi .UNINDENT .UNINDENT .sp New in version 0.0.2. .sp Changed in version 1.0: The type validation logic changed, see upgrading\&. .sp Changed in version 1.2: Added the \fBtypes_mapping\fP property and marked methods for testing types as deprecated. .SS Custom Validators .sp If a validation test doesn\(aqt depend on a specified constraint, it\(aqs possible to rather define these as validators than as a rule. They are called when the \fBvalidator\fP rule is given a string as constraint. A matching method with the prefix \fB_validator_\fP will be called with the field and value as argument: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C def _validator_oddity(self, field, value): if not value & 1: self._error(field, "Must be an odd number") .ft P .fi .UNINDENT .UNINDENT .SS Custom Coercers .sp You can also define custom methods that return a \fBcoerce\fP d value or point to a method as \fBrename_handler\fP\&. The method name must be prefixed with \fB_normalize_coerce_\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C class MyNormalizer(Validator): def __init__(self, multiplier, *args, **kwargs): super(MyNormalizer, self).__init__(*args, **kwargs) self.multiplier = multiplier def _normalize_coerce_multiply(self, value): return value * self.multiplier .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> schema = {\(aqfoo\(aq: {\(aqcoerce\(aq: \(aqmultiply\(aq}} >>> document = {\(aqfoo\(aq: 2} >>> MyNormalizer(2).normalized(document, schema) {\(aqfoo\(aq: 4} .ft P .fi .UNINDENT .UNINDENT .SS Custom Default Setters .sp Similar to custom rename handlers, it is also possible to create custom default setters. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from datetime import datetime class MyNormalizer(Validator): def _normalize_default_setter_utcnow(self, document): return datetime.utcnow() .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> schema = {\(aqcreation_date\(aq: {\(aqtype\(aq: \(aqdatetime\(aq, \(aqdefault_setter\(aq: \(aqutcnow\(aq}} >>> MyNormalizer().normalized({}, schema) {\(aqcreation_date\(aq: datetime.datetime(...)} .ft P .fi .UNINDENT .UNINDENT .SS Limitations .sp It may be a bad idea to overwrite particular contributed rules. .SS Instantiating Custom Validators .sp To make use of additional contextual information in a sub\-class of \fBValidator\fP, use a pattern like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C class MyValidator(Validator): def __init__(self, *args, **kwargs): if \(aqadditional_context\(aq in kwargs: self.additional_context = kwargs[\(aqadditional_context\(aq] super(MyValidator, self).__init__(*args, **kwargs) # alternatively define a property @property def additional_context(self): return self._config.get(\(aqadditional_context\(aq, \(aqbar\(aq) def _validate_type_foo(self, field, value): make_use_of(self.additional_context) .ft P .fi .UNINDENT .UNINDENT .sp This ensures that the additional context will be available in \fBValidator\fP child instances that may be used during validation. .sp New in version 0.9. .sp There\(aqs a function \fBvalidator_factory()\fP to get a \fBValidator\fP mutant with concatenated docstrings. .sp New in version 1.0. .SS Relevant \fIValidator\fP\-attributes .sp There are some attributes of a \fBValidator\fP that you should be aware of when writing custom Validators. .SS \fIValidator.document\fP .sp A validator accesses the \fBdocument\fP property when fetching fields for validation. It also allows validation of a field to happen in context of the rest of the document. .sp New in version 0.7.1. .SS \fIValidator.schema\fP .sp Alike, the \fBschema\fP property holds the used schema. .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 This attribute is not the same object that was passed as \fBschema\fP to the validator at some point. Also, its content may differ, though it still represents the initial constraints. It offers the same interface like a \fI\%dict\fP\&. .UNINDENT .UNINDENT .SS \fIValidator._error\fP .sp There are three signatures that are accepted to submit errors to the \fBValidator\fP\(aqs error stash. If necessary the given information will be parsed into a new instance of \fBValidationError\fP\&. .SS Full disclosure .sp In order to be able to gain complete insight into the context of an error at a later point, you need to call \fB_error()\fP with two mandatory arguments: .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 the field where the error occurred .IP \(bu 2 an instance of a \fBErrorDefinition\fP .UNINDENT .UNINDENT .UNINDENT .sp For custom rules you need to define an error as \fBErrorDefinition\fP with a unique id and the causing rule that is violated. See \fBerrors\fP for a list of the contributed error definitions. Keep in mind that bit 7 marks a group error, bit 5 marks an error raised by a validation against different sets of rules. .sp Optionally you can submit further arguments as information. Error handlers that are targeted for humans will use these as positional arguments when formatting a message with \fI\%str.format()\fP\&. Serializing handlers will keep these values in a list. .sp New in version 1.0. .SS Simple custom errors .sp A simpler form is to call \fB_error()\fP with the field and a string as message. However the resulting error will contain no information about the violated constraint. This is supposed to maintain backward compatibility, but can also be used when an in\-depth error handling isn\(aqt needed. .SS Multiple errors .sp When using child\-validators, it is a convenience to submit all their errors ; which is a list of \fBValidationError\fP instances. .sp New in version 1.0. .SS \fIValidator._get_child_validator\fP .sp If you need another instance of your \fBValidator\fP\-subclass, the \fB_get_child_validator()\fP\-method returns another instance that is initiated with the same arguments as \fBself\fP was. You can specify overriding keyword\-arguments. As the properties \fBdocument_path\fP and \fBschema_path\fP (see below) are inherited by the child validator, you can extend these by passing a single value or values\-tuple with the keywords \fBdocument_crumb\fP and \fBschema_crumb\fP\&. Study the source code for example usages. .sp New in version 0.9. .sp Changed in version 1.0: Added \fBdocument_crumb\fP and \fBschema_crumb\fP as optional keyword\- arguments. .SS \fIValidator.root_document\fP, \fI\&.root_schema\fP & \fIroot_allow_unknown\fP .sp A child\-validator \- as used when validating a \fBschema\fP \- can access the first generation validator\(aqs document and schema that are being processed as well as the constraints for unknown fields via its \fBroot_document\fP and \fBroot_schema\fP \fBroot_allow_unknown\fP\-properties. .sp New in version 1.0. .SS \fIValidator.document_path\fP & \fIValidator.schema_path\fP .sp These properties maintain the path of keys within the document respectively the schema that was traversed by possible parent\-validators. Both will be used as base path when an error is submitted. .sp New in version 1.0. .SS \fIValidator.recent_error\fP .sp The last single error that was submitted is accessible through the \fBrecent_error\fP\-attribute. .sp New in version 1.0. .SS \fIValidator.mandatory_validations\fP, \fIValidator.priority_validations\fP & \fIValidator._remaining_rules\fP .sp You can use these class properties and instance instance property if you want to adjust the validation logic for each field validation. \fBmandatory_validations\fP is a tuple that contains rules that will be validated for each field, regardless if the rule is defined for a field in a schema or not. \fBpriority_validations\fP is a tuple of ordered rules that will be validated before any other. \fB_remaining_rules\fP is a list that is populated under consideration of these and keeps track of the rules that are next in line to be evaluated. Thus it can be manipulated by rule handlers to change the remaining validation for the current field. Preferably you would call \fB_drop_remaining_rules()\fP to remove particular rules or all at once. .sp New in version 1.0. .sp Changed in version 1.2: Added \fB_remaining_rules\fP for extended leverage. .SS How to Contribute .sp Contributions are welcome! Not familiar with the codebase yet? No problem! There are many ways to contribute to open source projects: reporting bugs, helping with the documentation, spreading the word and of course, adding new features and patches. .SS Getting Started .INDENT 0.0 .IP 1. 3 Make sure you have a GitHub account. .IP 2. 3 Open a \fI\%new issue\fP, assuming one does not already exist. .IP 3. 3 Clearly describe the issue including steps to reproduce when it is a bug. .UNINDENT .SS Making Changes .INDENT 0.0 .IP \(bu 2 \fI\%Fork\fP the repository on GitHub. .IP \(bu 2 Create a topic branch from where you want to base your work. .IP \(bu 2 This is usually the \fBmaster\fP branch. .IP \(bu 2 Please avoid working directly on \fBmaster\fP branch. .IP \(bu 2 Make commits of logical units (if needed rebase your feature branch before submitting it). .IP \(bu 2 Check for unnecessary whitespace with \fBgit diff \-\-check\fP before committing. .IP \(bu 2 Make sure your commit messages are in the \fI\%proper format\fP\&. .IP \(bu 2 If your commit fixes an open issue, reference it in the commit message (#15). .IP \(bu 2 Make sure your code comforms to \fI\%PEP8\fP\&. .IP \(bu 2 Make sure you have added the necessary tests for your changes. .IP \(bu 2 Run all the tests to assure nothing else was accidentally broken. .IP \(bu 2 Don\(aqt forget to add yourself to \fI\%AUTHORS\fP\&. .UNINDENT .sp These guidelines also apply when helping with documentation (actually, for typos and minor additions you might choose to \fI\%fork and edit\fP). .SS Submitting Changes .INDENT 0.0 .IP \(bu 2 Push your changes to a topic branch in your fork of the repository. .IP \(bu 2 Submit a \fI\%Pull Request\fP\&. .IP \(bu 2 Wait for maintainer feedback. .UNINDENT .SS First time contributor? .sp It\(aqs alright. We\(aqve all been there. .SS Dont\(aq know where to start? .sp There are usually several TODO comments scattered around the codebase, maybe check them out and see if you have ideas, or can help with them. Also, check the \fI\%open issues\fP in case there\(aqs something that sparks your interest. What about documentation? I suck at english so if you\(aqre fluent with it (or notice any error), why not help with that? In any case, other than GitHub \fI\%help\fP pages, you might want to check this excellent \fI\%Effective Guide to Pull Requests\fP .SS Running the Tests .sp Cerberus runs under Python 2.6, 2.7, 3.3, 3.4, 3.5, PyPy and PyPy3. Therefore tests will be run in those four platforms in our \fI\%continuous integration server\fP\&. .sp The easiest way to get started is to run the tests in your local environment with: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ python setup.py test .ft P .fi .UNINDENT .UNINDENT .SS Testing with other Python versions .sp Before you submit a pull request, make sure your tests and changes run in all supported python versions: 2.6, 2.7, 3.3, 3.4 and PyPy. Instead of creating all those environments by hand, Cerberus uses \fI\%tox\fP\&. .sp Make sure you have all required python versions installed and run: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ pip install tox # First time only $ tox .ft P .fi .UNINDENT .UNINDENT .sp This might take some time the first run as the different virtual environments are created and dependencies are installed. If everything is ok, you will see the following: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C _________ summary _________ py26: commands succeeded py27: commands succeeded py33: commands succeeded py34: commands succeeded pypy: commands succeeded flake8: commands succeeded congratulations :) .ft P .fi .UNINDENT .UNINDENT .sp If something goes \fBwrong\fP and one test fails, you might need to run that test in the specific python version. You can use the created environments to run some specific tests. For example, if a test suite fails in Python 3.4: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ # From the project folder $ tox \-e py34 .ft P .fi .UNINDENT .UNINDENT .sp Have a look at \fB/tox.ini\fP for the available test environments and their workings. .SS Using Pytest .sp You also choose to run the whole test suite using \fI\%pytest\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ # Run the whole test suite $ py.test .ft P .fi .UNINDENT .UNINDENT .SS Using Docker .sp If you have a running \fI\%Docker\fP\-daemon running you can run tests from a container that has the necessary interpreters and packages installed and pass arguments to \fBtox\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ # in the project\(aqs root directory $ ./run\-docker\-tests \-e pypy3 \-e doctest .ft P .fi .UNINDENT .UNINDENT .sp You can run the script without any arguments to test the project exactly as \fI\%Continuous Integration\fP does without having to setup anything. The \fBtox\fP environments are preserved in a volume named \fBcerberus\-tox\fP, just remove it with \fBdocker volume rm\fP to clean them. .SS Building the HTML\-documentation .sp To preview the rendered HTML\-documentation you must intially install the documentation framework and a theme: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ # in the project\(aqs root directory $ pip install \-r requirements\-docs.txt .ft P .fi .UNINDENT .UNINDENT .sp The HTML build is triggered with: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ # in \(aqdocs\(aq\-folder $ make html .ft P .fi .UNINDENT .UNINDENT .sp The result can be accessed by opening \fBdocs/_build/html/index.html\fP\&. .SS Continuous Integration .sp Each time code is pushed to the \fBmaster\fP branch the whole test\-suite is executed on \fI\%Travis\-CI\fP\&. This is also the case for pull\-requests. A box at the bottom of its conversation\-view will inform about the tests\(aq status. The contributor can then fix the code, add commits, \fI\%squash\fP the commits and push again. The CI will also run \fI\%flake8\fP so make sure that your code complies to PEP8 and test links and sample\-code in the documentation. .SS Source Code .sp Source code is available at \fI\%GitHub\fP\&. .SS Funding .sp We believe that collaboratively funded software can offer outstanding returns on investment, by encouraging users to collectively share the cost of development. .sp Cerberus continues to be open\-source and permissively licensed, but we firmly believe it is in the commercial best\-interest for users of the project to invest in its ongoing development. .sp Signing up as a Backer: .INDENT 0.0 .IP \(bu 2 Directly contribute to faster releases, more features, and higher quality software. .IP \(bu 2 Allow more time to be invested in documentation, issue triage, and community support. .IP \(bu 2 Safeguard the future development of Cerberus. .UNINDENT .sp If you run a business and is using Cerberus in a revenue\-generating product, it would make business sense to sponsor its development: it ensures the project that your product relies on stays healthy and actively maintained. It can also help your exposure in the Cerberus community and makes it easier to attract Cerberus developers. .sp Of course, individual users are also welcome to make a recurring pledge if Cerberus has helped you in your work or personal projects. Alternatively, consider donating as a sign of appreciation \- like buying me coffee once in a while :) .SS Support Cerberus development .sp You can support Cerberus development by pledging on Patreon or donating on PayPal. .INDENT 0.0 .IP \(bu 2 \fI\%Become a Backer\fP (recurring pledge) .IP \(bu 2 \fI\%Donate via PayPal\fP (one time) .UNINDENT .SS API Documentation .SS Validator Class .INDENT 0.0 .TP .B 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 \fI\%validate()\fP, \fI\%validated()\fP or \fI\%normalized()\fP method. An instance itself is callable and executes a validation. .sp All instantiation parameters are optional. .sp There are the introspective properties \fBtypes\fP, \fBvalidators\fP, \fBcoercers\fP, \fBdefault_setters\fP, \fBrules\fP, \fBnormalization_rules\fP and \fBvalidation_rules\fP\&. .sp The attributes reflecting the available rules are assembled considering constraints that are defined in the docstrings of rules\(aq methods and is effectively used as validation schema for \fI\%schema\fP\&. .INDENT 7.0 .TP .B Parameters .INDENT 7.0 .IP \(bu 2 \fBschema\fP (any \fI\%mapping\fP) \-\- See \fI\%schema\fP\&. Defaults to \fI\%None\fP\&. .IP \(bu 2 \fBignore_none_values\fP (\fI\%bool\fP) \-\- See \fI\%ignore_none_values\fP\&. Defaults to \fBFalse\fP\&. .IP \(bu 2 \fBallow_unknown\fP (\fI\%bool\fP or any \fI\%mapping\fP) \-\- See \fI\%allow_unknown\fP\&. Defaults to \fBFalse\fP\&. .IP \(bu 2 \fBpurge_unknown\fP (\fI\%bool\fP) \-\- See \fI\%purge_unknown\fP\&. Defaults to to \fBFalse\fP\&. .IP \(bu 2 \fBerror_handler\fP (class or instance based on \fI\%BaseErrorHandler\fP or \fI\%tuple\fP) \-\- The error handler that formats the result of \fI\%errors\fP\&. 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: \fI\%BasicErrorHandler\fP\&. .UNINDENT .UNINDENT .INDENT 7.0 .TP .B _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. .UNINDENT .INDENT 7.0 .TP .B _error(*args) Creates and adds one or multiple errors. .INDENT 7.0 .TP .B Parameters \fBargs\fP \-\- .sp Accepts different argument\(aqs signatures. .sp \fI1. Bulk addition of errors:\fP .INDENT 7.0 .IP \(bu 2 \fI\%iterable\fP of \fI\%ValidationError\fP\-instances .UNINDENT .sp The errors will be added to \fB_errors\fP\&. .sp \fI2. Custom error:\fP .INDENT 7.0 .IP \(bu 2 the invalid field\(aqs name .IP \(bu 2 the error message .UNINDENT .sp A custom error containing the message will be created and added to \fB_errors\fP\&. There will however be fewer information contained in the error (no reference to the violated rule and its constraint). .sp \fI3. Defined error:\fP .INDENT 7.0 .IP \(bu 2 the invalid field\(aqs name .IP \(bu 2 the error\-reference, see \fBcerberus.errors\fP .IP \(bu 2 arbitrary, supplemental information about the error .UNINDENT .sp A \fI\%ValidationError\fP instance will be created and added to \fB_errors\fP\&. .UNINDENT .UNINDENT .INDENT 7.0 .TP .B _get_child_validator(document_crumb=None, schema_crumb=None, **kwargs) .INDENT 7.0 .TP .B 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 \fIkeyword\fP\-parameter. .UNINDENT .INDENT 7.0 .TP .B Parameters .INDENT 7.0 .IP \(bu 2 \fBdocument_crumb\fP (\fI\%tuple\fP or \fI\%hashable\fP) \-\- Extends the \fBdocument_path\fP of the child\-validator. .IP \(bu 2 \fBschema_crumb\fP (\fI\%tuple\fP or hashable) \-\- Extends the \fBschema_path\fP of the child\-validator. .IP \(bu 2 \fBkwargs\fP (\fI\%dict\fP) \-\- Overriding keyword\-arguments for initialization. .UNINDENT .TP .B Returns an instance of \fBself.__class__\fP .UNINDENT .UNINDENT .INDENT 7.0 .TP .B _lookup_field(path) .INDENT 7.0 .TP .B Searches for a field as defined by path. This method is used by the \fBdependency\fP evaluation logic. .UNINDENT .INDENT 7.0 .TP .B Parameters \fBpath\fP (\fI\%str\fP) \-\- Path elements are separated by a \fB\&.\fP\&. A leading \fB^\fP indicates that the path relates to the document root, otherwise it relates to the currently evaluated document, which is possibly a subdocument. The sequence \fB^^\fP at the start will be interpreted as a literal \fB^\fP\&. .TP .B Returns Either the found field name and its value or \fI\%None\fP for both. .TP .B Return type A two\-value \fI\%tuple\fP\&. .UNINDENT .UNINDENT .INDENT 7.0 .TP .B allow_unknown If \fBTrue\fP 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: \fI\%bool\fP or any \fI\%mapping\fP .UNINDENT .INDENT 7.0 .TP .B classmethod clear_caches() Purge the cache of known valid schemas. .UNINDENT .INDENT 7.0 .TP .B errors The errors of the last processing formatted by the handler that is bound to \fBerror_handler\fP\&. .UNINDENT .INDENT 7.0 .TP .B ignore_none_values Whether to not process \fI\%None\fP\-values in a document or not. Type: \fI\%bool\fP .UNINDENT .INDENT 7.0 .TP .B is_child \fBTrue\fP for child\-validators obtained with \fI\%_get_child_validator()\fP\&. Type: \fI\%bool\fP .UNINDENT .INDENT 7.0 .TP .B normalized(document, schema=None, always_return_document=False) Returns the document normalized according to the specified rules of a schema. .INDENT 7.0 .TP .B Parameters .INDENT 7.0 .IP \(bu 2 \fBdocument\fP (any \fI\%mapping\fP) \-\- The document to normalize. .IP \(bu 2 \fBschema\fP (any \fI\%mapping\fP) \-\- The validation schema. Defaults to \fI\%None\fP\&. If not provided here, the schema must have been provided at class instantiation. .IP \(bu 2 \fBalways_return_document\fP (\fI\%bool\fP) \-\- Return the document, even if an error occurred. Defaults to: \fBFalse\fP\&. .UNINDENT .TP .B Returns A normalized copy of the provided mapping or \fI\%None\fP if an error occurred during normalization. .UNINDENT .UNINDENT .INDENT 7.0 .TP .B purge_unknown If \fBTrue\fP unknown fields will be deleted from the document unless a validation is called with disabled normalization. Also see purging\-unknown\-fields\&. Type: \fI\%bool\fP .UNINDENT .INDENT 7.0 .TP .B root_allow_unknown The \fI\%allow_unknown\fP attribute of the first level ancestor of a child validator. .UNINDENT .INDENT 7.0 .TP .B root_document The \fBdocument\fP attribute of the first level ancestor of a child validator. .UNINDENT .INDENT 7.0 .TP .B root_schema The \fI\%schema\fP attribute of the first level ancestor of a child validator. .UNINDENT .INDENT 7.0 .TP .B rules_set_registry The registry that holds referenced rules sets. Type: \fI\%Registry\fP .UNINDENT .INDENT 7.0 .TP .B schema The validation schema of a validator. When a schema is passed to a method, it replaces this attribute. Type: any \fI\%mapping\fP or \fI\%None\fP .UNINDENT .INDENT 7.0 .TP .B schema_registry The registry that holds referenced schemas. Type: \fI\%Registry\fP .UNINDENT .INDENT 7.0 .TP .B validate(document, schema=None, update=False, normalize=True) Normalizes and validates a mapping against a validation\-schema of defined rules. .INDENT 7.0 .TP .B Parameters .INDENT 7.0 .IP \(bu 2 \fBdocument\fP (any \fI\%mapping\fP) \-\- The document to normalize. .IP \(bu 2 \fBschema\fP (any \fI\%mapping\fP) \-\- The validation schema. Defaults to \fI\%None\fP\&. If not provided here, the schema must have been provided at class instantiation. .IP \(bu 2 \fBupdate\fP (\fI\%bool\fP) \-\- If \fBTrue\fP, required fields won\(aqt be checked. .IP \(bu 2 \fBnormalize\fP (\fI\%bool\fP) \-\- If \fBTrue\fP, normalize the document before validation. .UNINDENT .TP .B Returns \fBTrue\fP if validation succeeds, otherwise \fBFalse\fP\&. Check the \fI\%errors()\fP property for a list of processing errors. .TP .B Return type \fI\%bool\fP .UNINDENT .UNINDENT .INDENT 7.0 .TP .B validated(*args, **kwargs) Wrapper around \fI\%validate()\fP that returns the normalized and validated document or \fI\%None\fP if validation failed. .UNINDENT .UNINDENT .SS Rules Set & Schema Registry .INDENT 0.0 .TP .B 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. .INDENT 7.0 .TP .B Parameters \fBdefinitions\fP (any \fI\%mapping\fP) \-\- Optional, initial definitions. .UNINDENT .INDENT 7.0 .TP .B add(name, definition) Register a definition to the registry. Existing definitions are replaced silently. .INDENT 7.0 .TP .B Parameters .INDENT 7.0 .IP \(bu 2 \fBname\fP (\fI\%str\fP) \-\- The name which can be used as reference in a validation schema. .IP \(bu 2 \fBdefinition\fP (any \fI\%mapping\fP) \-\- The definition. .UNINDENT .UNINDENT .UNINDENT .INDENT 7.0 .TP .B all() Returns a \fI\%dict\fP with all registered definitions mapped to their name. .UNINDENT .INDENT 7.0 .TP .B clear() Purge all definitions in the registry. .UNINDENT .INDENT 7.0 .TP .B extend(definitions) Add several definitions at once. Existing definitions are replaced silently. .INDENT 7.0 .TP .B Parameters \fBdefinitions\fP (a \fI\%mapping\fP or an \fI\%iterable\fP with two\-value \fI\%tuple\fP s) \-\- The names and definitions. .UNINDENT .UNINDENT .INDENT 7.0 .TP .B get(name, default=None) Retrieve a definition from the registry. .INDENT 7.0 .TP .B Parameters .INDENT 7.0 .IP \(bu 2 \fBname\fP (\fI\%str\fP) \-\- The reference that points to the definition. .IP \(bu 2 \fBdefault\fP \-\- Return value if the reference isn\(aqt registered. .UNINDENT .UNINDENT .UNINDENT .INDENT 7.0 .TP .B remove(*names) Unregister definitions from the registry. .INDENT 7.0 .TP .B Parameters \fBnames\fP \-\- The names of the definitions that are to be unregistered. .UNINDENT .UNINDENT .UNINDENT .SS Type Definitions .INDENT 0.0 .TP .B class cerberus.TypeDefinition(name, included_types, excluded_types) This class is used to define types that can be used as value in the \fBtypes_mapping\fP property. The \fBname\fP should 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 in \fBincluded_types\fP and must not match any of the types contained in \fBexcluded_types\fP\&. .UNINDENT .SS Error Handlers .INDENT 0.0 .TP .B class cerberus.errors.BaseErrorHandler(*args, **kwargs) Base class for all error handlers. Subclasses are identified as error\-handlers with an instance\-test. .INDENT 7.0 .TP .B __call__(errors) Returns errors in a handler\-specific format. .INDENT 7.0 .TP .B Parameters \fBerrors\fP (\fI\%iterable\fP of \fI\%ValidationError\fP instances or a \fI\%Validator\fP instance) \-\- An object containing the errors. .UNINDENT .UNINDENT .INDENT 7.0 .TP .B __init__(*args, **kwargs) Optionally initialize a new instance. .UNINDENT .INDENT 7.0 .TP .B __iter__() Be a superhero and implement an iterator over errors. .UNINDENT .INDENT 7.0 .TP .B __weakref__ list of weak references to the object (if defined) .UNINDENT .INDENT 7.0 .TP .B add(error) Add an error to the errors\(aq container object of a handler. .INDENT 7.0 .TP .B Parameters \fBerror\fP (\fI\%ValidationError\fP) \-\- The error to add. .UNINDENT .UNINDENT .INDENT 7.0 .TP .B emit(error) .INDENT 7.0 .TP .B Optionally emits an error in the handler\(aqs format to a stream. Or light a LED, or even shut down a power plant. .UNINDENT .INDENT 7.0 .TP .B Parameters \fBerror\fP (\fI\%ValidationError\fP) \-\- The error to emit. .UNINDENT .UNINDENT .INDENT 7.0 .TP .B end(validator) Gets called when a validation ends. .INDENT 7.0 .TP .B Parameters \fBvalidator\fP (\fI\%Validator\fP) \-\- The calling validator. .UNINDENT .UNINDENT .INDENT 7.0 .TP .B extend(errors) Adds all errors to the handler\(aqs container object. .INDENT 7.0 .TP .B Parameters \fBerrors\fP (\fI\%iterable\fP of \fI\%ValidationError\fP instances) \-\- The errors to add. .UNINDENT .UNINDENT .INDENT 7.0 .TP .B start(validator) Gets called when a validation starts. .INDENT 7.0 .TP .B Parameters \fBvalidator\fP (\fI\%Validator\fP) \-\- The calling validator. .UNINDENT .UNINDENT .UNINDENT .INDENT 0.0 .TP .B class cerberus.errors.BasicErrorHandler(tree=None) Models cerberus\(aq legacy. Returns a \fI\%dict\fP\&. When mangled through \fI\%str\fP a pretty\-formatted representation of that tree is returned. .UNINDENT .SS Python Error Representations .INDENT 0.0 .TP .B class cerberus.errors.ErrorDefinition(code, rule) This class is used to define possible errors. Each distinguishable error is defined by a \fIunique\fP error \fBcode\fP as integer and the \fBrule\fP that can cause it as string. The instances\(aq names do not contain a common prefix as they are supposed to be referenced within the module namespace, e.g. \fBerrors.CUSTOM\fP\&. .UNINDENT .INDENT 0.0 .TP .B class cerberus.errors.ValidationError(document_path, schema_path, code, rule, constraint, value, info) A simple class to store and query basic error information. .INDENT 7.0 .TP .B child_errors A list that contains the individual errors of a bulk validation error. .UNINDENT .INDENT 7.0 .TP .B code = None The error\(aqs identifier code. Type: \fI\%int\fP .UNINDENT .INDENT 7.0 .TP .B constraint = None The constraint that failed. .UNINDENT .INDENT 7.0 .TP .B definitions_errors Dictionary with errors of an .nf * .fi of\-rule mapped to the index of the definition it occurred in. Returns \fI\%None\fP if not applicable. .UNINDENT .INDENT 7.0 .TP .B document_path = None The path to the field within the document that caused the error. Type: \fI\%tuple\fP .UNINDENT .INDENT 7.0 .TP .B field Field of the contextual mapping, possibly \fI\%None\fP\&. .UNINDENT .INDENT 7.0 .TP .B info = None May hold additional information about the error. Type: \fI\%tuple\fP .UNINDENT .INDENT 7.0 .TP .B is_group_error \fBTrue\fP for errors of bulk validations. .UNINDENT .INDENT 7.0 .TP .B is_logic_error \fBTrue\fP for validation errors against different schemas with .nf * .fi of\-rules. .UNINDENT .INDENT 7.0 .TP .B is_normalization_error \fBTrue\fP for normalization errors. .UNINDENT .INDENT 7.0 .TP .B rule = None The rule that failed. Type: \fIstring\fP .UNINDENT .INDENT 7.0 .TP .B schema_path = None The path to the rule within the schema that caused the error. Type: \fI\%tuple\fP .UNINDENT .INDENT 7.0 .TP .B value = None The value that failed. .UNINDENT .UNINDENT .SS Error Codes .sp These errors are used as \fI\%code\fP\&. .TS center; |l|l|l|l|. _ T{ Code (dec.) T} T{ Code (hex.) T} T{ Name T} T{ Rule T} _ T{ 2 T} T{ 0x2 T} T{ REQUIRED_FIELD T} T{ required T} _ T{ 4 T} T{ 0x4 T} T{ DEPENDENCIES_FIELD T} T{ dependencies T} _ T{ 5 T} T{ 0x5 T} T{ DEPENDENCIES_FIELD_VALUE T} T{ dependencies T} _ T{ 6 T} T{ 0x6 T} T{ EXCLUDES_FIELD T} T{ excludes T} _ T{ 34 T} T{ 0x22 T} T{ EMPTY_NOT_ALLOWED T} T{ empty T} _ T{ 35 T} T{ 0x23 T} T{ NOT_NULLABLE T} T{ nullable T} _ T{ 36 T} T{ 0x24 T} T{ BAD_TYPE T} T{ type T} _ T{ 37 T} T{ 0x25 T} T{ BAD_TYPE_FOR_SCHEMA T} T{ schema T} _ T{ 38 T} T{ 0x26 T} T{ ITEMS_LENGTH T} T{ items T} _ T{ 39 T} T{ 0x27 T} T{ MIN_LENGTH T} T{ minlength T} _ T{ 40 T} T{ 0x28 T} T{ MAX_LENGTH T} T{ maxlength T} _ T{ 65 T} T{ 0x41 T} T{ REGEX_MISMATCH T} T{ regex T} _ T{ 66 T} T{ 0x42 T} T{ MIN_VALUE T} T{ min T} _ T{ 67 T} T{ 0x43 T} T{ MAX_VALUE T} T{ max T} _ T{ 68 T} T{ 0x44 T} T{ UNALLOWED_VALUE T} T{ allowed T} _ T{ 69 T} T{ 0x45 T} T{ UNALLOWED_VALUES T} T{ allowed T} _ T{ 70 T} T{ 0x46 T} T{ FORBIDDEN_VALUE T} T{ forbidden T} _ T{ 71 T} T{ 0x47 T} T{ FORBIDDEN_VALUES T} T{ forbidden T} _ T{ 97 T} T{ 0x61 T} T{ COERCION_FAILED T} T{ coerce T} _ T{ 98 T} T{ 0x62 T} T{ RENAMING_FAILED T} T{ rename_handler T} _ T{ 99 T} T{ 0x63 T} T{ READONLY_FIELD T} T{ readonly T} _ T{ 100 T} T{ 0x64 T} T{ SETTING_DEFAULT_FAILED T} T{ default_setter T} _ T{ 129 T} T{ 0x81 T} T{ MAPPING_SCHEMA T} T{ schema T} _ T{ 130 T} T{ 0x82 T} T{ SEQUENCE_SCHEMA T} T{ schema T} _ T{ 131 T} T{ 0x83 T} T{ KEYSCHEMA T} T{ keyschema T} _ T{ 132 T} T{ 0x84 T} T{ VALUESCHEMA T} T{ valueschema T} _ T{ 143 T} T{ 0x8f T} T{ BAD_ITEMS T} T{ items T} _ T{ 145 T} T{ 0x91 T} T{ NONEOF T} T{ noneof T} _ T{ 146 T} T{ 0x92 T} T{ ONEOF T} T{ oneof T} _ T{ 147 T} T{ 0x93 T} T{ ANYOF T} T{ anyof T} _ T{ 148 T} T{ 0x94 T} T{ ALLOF T} T{ allof T} _ .TE .SS Error Containers .INDENT 0.0 .TP .B class cerberus.errors.ErrorList A list for \fI\%ValidationError\fP instances that can be queried with the \fBin\fP keyword for a particular \fI\%ErrorDefinition\fP\&. .UNINDENT .INDENT 0.0 .TP .B class cerberus.errors.ErrorTree(errors=[]) Base class for \fI\%DocumentErrorTree\fP and \fI\%SchemaErrorTree\fP\&. .INDENT 7.0 .TP .B add(error) Add an error to the tree. .INDENT 7.0 .TP .B Parameters \fBerror\fP \-\- \fI\%ValidationError\fP .UNINDENT .UNINDENT .INDENT 7.0 .TP .B fetch_errors_from(path) Returns all errors for a particular path. .INDENT 7.0 .TP .B Parameters \fBpath\fP \-\- \fI\%tuple\fP of \fI\%hashable\fP s. .TP .B Return type \fI\%ErrorList\fP .UNINDENT .UNINDENT .INDENT 7.0 .TP .B fetch_node_from(path) Returns a node for a path. .INDENT 7.0 .TP .B Parameters \fBpath\fP \-\- Tuple of \fI\%hashable\fP s. .TP .B Return type \fBErrorTreeNode\fP or \fI\%None\fP .UNINDENT .UNINDENT .UNINDENT .INDENT 0.0 .TP .B class cerberus.errors.DocumentErrorTree(errors=[]) Implements a dict\-like class to query errors by indexes following the structure of a validated document. .UNINDENT .INDENT 0.0 .TP .B class cerberus.errors.SchemaErrorTree(errors=[]) Implements a dict\-like class to query errors by indexes following the structure of the used schema. .UNINDENT .SS Exceptions .INDENT 0.0 .TP .B exception cerberus.SchemaError Raised when the validation schema is missing, has the wrong format or contains errors. .UNINDENT .INDENT 0.0 .TP .B exception cerberus.DocumentError Raised when the target document is missing or has the wrong format .UNINDENT .SS Utilities .INDENT 0.0 .TP .B class cerberus.utils.TypeDefinition(name, included_types, excluded_types) This class is used to define types that can be used as value in the \fBtypes_mapping\fP property. The \fBname\fP should 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 in \fBincluded_types\fP and must not match any of the types contained in \fBexcluded_types\fP\&. .INDENT 7.0 .TP .B excluded_types Alias for field number 2 .UNINDENT .INDENT 7.0 .TP .B included_types Alias for field number 1 .UNINDENT .INDENT 7.0 .TP .B name Alias for field number 0 .UNINDENT .UNINDENT .INDENT 0.0 .TP .B 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. .UNINDENT .INDENT 0.0 .TP .B class cerberus.utils.readonly_classproperty .UNINDENT .INDENT 0.0 .TP .B cerberus.utils.validator_factory(name, bases=None, namespace={}) .INDENT 7.0 .TP .B Dynamically create a \fI\%Validator\fP subclass. Docstrings of mixin\-classes will be added to the resulting class\(aq one if \fB__doc__\fP is not in \fBnamespace\fP\&. .UNINDENT .INDENT 7.0 .TP .B Parameters .INDENT 7.0 .IP \(bu 2 \fBname\fP (\fI\%str\fP) \-\- The name of the new class. .IP \(bu 2 \fBbases\fP (\fI\%tuple\fP of or a single \fI\%class\fP) \-\- Class(es) with additional and overriding attributes. .IP \(bu 2 \fBnamespace\fP (\fI\%dict\fP) \-\- Attributes for the new class. .UNINDENT .TP .B Returns The created class. .UNINDENT .UNINDENT .SS Schema Validation Schema .sp Against this schema validation schemas given to a vanilla \fI\%Validator\fP will be validated: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C {\(aqallof\(aq: {\(aqlogical\(aq: \(aqallof\(aq, \(aqtype\(aq: \(aqlist\(aq}, \(aqallow_unknown\(aq: {\(aqoneof\(aq: [{\(aqtype\(aq: \(aqboolean\(aq}, {\(aqtype\(aq: [\(aqdict\(aq, \(aqstring\(aq], \(aqvalidator\(aq: \(aqbulk_schema\(aq}]}, \(aqallowed\(aq: {\(aqtype\(aq: \(aqlist\(aq}, \(aqanyof\(aq: {\(aqlogical\(aq: \(aqanyof\(aq, \(aqtype\(aq: \(aqlist\(aq}, \(aqcoerce\(aq: {\(aqoneof\(aq: [{\(aqtype\(aq: \(aqcallable\(aq}, {\(aqschema\(aq: {\(aqoneof\(aq: [{\(aqtype\(aq: \(aqcallable\(aq}, {\(aqallowed\(aq: (), \(aqtype\(aq: \(aqstring\(aq}]}, \(aqtype\(aq: \(aqlist\(aq}, {\(aqallowed\(aq: (), \(aqtype\(aq: \(aqstring\(aq}]}, \(aqdefault\(aq: {\(aqnullable\(aq: True}, \(aqdefault_setter\(aq: {\(aqoneof\(aq: [{\(aqtype\(aq: \(aqcallable\(aq}, {\(aqallowed\(aq: (), \(aqtype\(aq: \(aqstring\(aq}]}, \(aqdependencies\(aq: {\(aqtype\(aq: (\(aqdict\(aq, \(aqhashable\(aq, \(aqlist\(aq), \(aqvalidator\(aq: \(aqdependencies\(aq}, \(aqempty\(aq: {\(aqtype\(aq: \(aqboolean\(aq}, \(aqexcludes\(aq: {\(aqschema\(aq: {\(aqtype\(aq: \(aqhashable\(aq}, \(aqtype\(aq: (\(aqhashable\(aq, \(aqlist\(aq)}, \(aqforbidden\(aq: {\(aqtype\(aq: \(aqlist\(aq}, \(aqitems\(aq: {\(aqtype\(aq: \(aqlist\(aq, \(aqvalidator\(aq: \(aqitems\(aq}, \(aqkeyschema\(aq: {\(aqforbidden\(aq: [\(aqrename\(aq, \(aqrename_handler\(aq], \(aqtype\(aq: [\(aqdict\(aq, \(aqstring\(aq], \(aqvalidator\(aq: \(aqbulk_schema\(aq}, \(aqmax\(aq: {\(aqnullable\(aq: False}, \(aqmaxlength\(aq: {\(aqtype\(aq: \(aqinteger\(aq}, \(aqmin\(aq: {\(aqnullable\(aq: False}, \(aqminlength\(aq: {\(aqtype\(aq: \(aqinteger\(aq}, \(aqnoneof\(aq: {\(aqlogical\(aq: \(aqnoneof\(aq, \(aqtype\(aq: \(aqlist\(aq}, \(aqnullable\(aq: {\(aqtype\(aq: \(aqboolean\(aq}, \(aqoneof\(aq: {\(aqlogical\(aq: \(aqoneof\(aq, \(aqtype\(aq: \(aqlist\(aq}, \(aqpurge_unknown\(aq: {\(aqtype\(aq: \(aqboolean\(aq}, \(aqreadonly\(aq: {\(aqtype\(aq: \(aqboolean\(aq}, \(aqregex\(aq: {\(aqtype\(aq: \(aqstring\(aq}, \(aqrename\(aq: {\(aqtype\(aq: \(aqhashable\(aq}, \(aqrename_handler\(aq: {\(aqoneof\(aq: [{\(aqtype\(aq: \(aqcallable\(aq}, {\(aqschema\(aq: {\(aqoneof\(aq: [{\(aqtype\(aq: \(aqcallable\(aq}, {\(aqallowed\(aq: (), \(aqtype\(aq: \(aqstring\(aq}]}, \(aqtype\(aq: \(aqlist\(aq}, {\(aqallowed\(aq: (), \(aqtype\(aq: \(aqstring\(aq}]}, \(aqrequired\(aq: {\(aqtype\(aq: \(aqboolean\(aq}, \(aqschema\(aq: {\(aqanyof\(aq: [{\(aqvalidator\(aq: \(aqschema\(aq}, {\(aqvalidator\(aq: \(aqbulk_schema\(aq}], \(aqtype\(aq: [\(aqdict\(aq, \(aqstring\(aq]}, \(aqtype\(aq: {\(aqtype\(aq: [\(aqstring\(aq, \(aqlist\(aq], \(aqvalidator\(aq: \(aqtype\(aq}, \(aqvalidator\(aq: {\(aqoneof\(aq: [{\(aqtype\(aq: \(aqcallable\(aq}, {\(aqschema\(aq: {\(aqoneof\(aq: [{\(aqtype\(aq: \(aqcallable\(aq}, {\(aqallowed\(aq: (), \(aqtype\(aq: \(aqstring\(aq}]}, \(aqtype\(aq: \(aqlist\(aq}, {\(aqallowed\(aq: (), \(aqtype\(aq: \(aqstring\(aq}]}, \(aqvalueschema\(aq: {\(aqforbidden\(aq: [\(aqrename\(aq, \(aqrename_handler\(aq], \(aqtype\(aq: [\(aqdict\(aq, \(aqstring\(aq], \(aqvalidator\(aq: \(aqbulk_schema\(aq}} .ft P .fi .UNINDENT .UNINDENT .SS Frequently Asked Questions .SS Can I use Cerberus to validate objects? .sp Yes. See \fI\%Validating user objects with Cerberus\fP\&. .SS External resources .sp Here are some recommended resources that deal with Cerberus. If you find something interesting on the web, please amend it to this document and open a pull request (see contribute). .SS 7 Best Python Libraries For Validating Data (February 2018) .sp \fI\%Clickbait\fP that mentions Cerberus. It\(aqs a starting point to compare libraries with a similar scope though. .SS Nicola Iarocci: Cerberus, or Data Validation for Humans (November 2017) .sp Get fastened for the full tour on Cerberus that Nicola gave in a \fI\%talk\fP at PiterPy 2017. No bit is missed, so don\(aqt miss it! The talk also includes a sample of the actual pronunciation of Iarocci as extra takeaway. .SS Henry Ölsner: Validate JSON data using cerberus (March 2016) .sp In this \fI\%blog post\fP the author describes how to validate network configurations with a schema noted in YAML. The article that doesn\(aqt spare on code snippets develops the resulting schema by gradually increasing its complexity. A custom type check is also implemented, but be aware that version \fI0.9.2\fP is used. With 1.0 and later the implementation should look like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C def _validate_type_ipv4address(self, value): try: ipaddress.IPv4Address(value) except: return False else: return True .ft P .fi .UNINDENT .UNINDENT .SS Cerberus changelog .sp Here you can see the full list of changes between each Cerberus release. .SS Version 1.2 .sp Cerberus is a collaboratively funded project, see the \fI\%funding page\fP\&. .sp Released on April 12, 2018. .INDENT 0.0 .IP \(bu 2 New: docs: Add note that normalization cannot be applied within an .nf * .fi of\-rule. (Frank Sachsenheim) .IP \(bu 2 New: Add the ability to query for a type of error in an error tree. (Frank Sachsenheim) .IP \(bu 2 New: Add errors.MAPPING_SCHEMA on errors within subdocuments. (Frank Sachsenheim) .IP \(bu 2 New: Support for Types Definitions, which allow quick types check on the fly (Frank Sachsenheim). .IP \(bu 2 Fix: Simplify the tests with Docker by using a volume for tox environments. (Frank Sachsenheim) .IP \(bu 2 Fix: Schema registries do not work on dict fields. Closes \fI\%#318\fP\&. (Frank Sachsenheim) .IP \(bu 2 Fix: Need to drop some rules when \fBempty\fP is allowed. Closes \fI\%#326\fP\&. (Frank Sachsenheim) .IP \(bu 2 Fix: typo in README (Christian Hogan). .IP \(bu 2 Fix: Make \fBpurge_unknown\fP and \fBallow_unknown\fP play nice together. Closes \fI\%#324\fP\&. (Audric Schiltknecht) .IP \(bu 2 Fix: API reference lacks generated content. Closes \fI\%#281\fP\&. (Frank Sachsenheim) .IP \(bu 2 Fix: \fBreadonly\fP works properly just in the first validation. Closes \fI\%#311\fP\&. (Frank Sachsenheim) .IP \(bu 2 Fix: \fBcoerce\fP ignores \fBnullable: True\fP\&. Closes \fI\%#269\fP\&. (Frank Sachsenheim) .IP \(bu 2 Fix: A dependency is not considered satisfied if it has a null value. Closes \fI\%#305\fP\&. (Frank Sachsenheim) .IP \(bu 2 Override \fBUnvalidatedSchema.copy\fP (Peter Demin). .IP \(bu 2 Fix: README link. (Gabriel Wainer) .IP \(bu 2 Fix: Regression: allow_unknown causes dictionary validation to fail with a KeyError. Closes \fI\%#302\fP\&. (Frank Sachsenheim) .IP \(bu 2 Fix: Error when setting fields as tuples instead of lists. Closes \fI\%#271\fP\&. (Sebastian Rajo) .IP \(bu 2 Fix: Correctly handle nested logic and group errors. Closes \fI\%#278\fP and \fI\%#299\fP\&. (Kornelijus Survila) .IP \(bu 2 CI: Reactivate testing on PyPy3. (Frank Sachsenheim) .UNINDENT .SS Version 1.1 .sp Released on January 25, 2017. .INDENT 0.0 .IP \(bu 2 New: Python 3.6 support (Frank Sachsenheim) .IP \(bu 2 New: Users can implement their own semantics in Validator._lookup_field (Frank Sachsenheim). .IP \(bu 2 New: Allow applying of \fBempty\fP rule to sequences and mappings. Closes \fI\%#270\fP\&. (Frank Sachsenheim) .IP \(bu 2 Fix: Better handling of unicode in \fBallowed\fP rule. Closes \fI\%#280\fP\&. (Michael Klich) .IP \(bu 2 Fix: Rules sets with normalization rules fail. Closes \fI\%#283\fP\&. (Frank Sachsenheim) .IP \(bu 2 Fix: Spelling error in RULE_SCHEMA_SEPARATOR constant (Antoine Lubineau) .IP \(bu 2 Fix: Expand schemas and rules sets when added to a registry. Closes \fI\%#284\fP (Frank Sachsenheim) .IP \(bu 2 Fix: \fBreadonly\fP conflicts with \fBdefault\fP rule. Closes \fI\%#268\fP (Dominik Kellner). .IP \(bu 2 Fix: Creating custom Validator instance with \fB_validator_*\fP method raises \fBSchemaError\fP\&. Closes \fI\%#265\fP (Frank Sachsenheim). .IP \(bu 2 Fix: Consistently use new style classes (Dominik Kellner). .IP \(bu 2 Fix: \fBNotImplemented\fP does not derive from \fBBaseException\fP (Bryan W. Weber). .IP \(bu 2 Completely switch to py.test. Closes \fI\%#213\fP (Frank Sachsenheim). .IP \(bu 2 Convert \fBself.assert\fP method calls to plain \fBassert\fP calls supported by pytest. Addresses \fI\%#213\fP (Bruno Oliveira). .IP \(bu 2 Docs: Clarifications concerning dependencies and unique rules (Frank Sachsenheim) .IP \(bu 2 Docs: Fix custom coerces documentation. Closes \fI\%#285\fP (gilbsgilbs). .IP \(bu 2 Docs: Add note concerning regex flags. Closes \fI\%#173\fP (Frank Sachsenheim). .IP \(bu 2 Docs: Explain that normalization and coercion are performed on a copy of the original document (Sergey Leshchenko). .UNINDENT .SS Version 1.0.1 .sp Released on September 1, 2016. .INDENT 0.0 .IP \(bu 2 Fix: bump trove classifier to Production/Stable (5). .UNINDENT .SS Version 1.0 .sp Released on September 1, 2016. .sp \fBWARNING:\fP .INDENT 0.0 .INDENT 3.5 This is a major release which breaks backward compatibility in several ways. Don\(aqt worry, these changes are for the better. However, if you are upgrading, then you should really take the time to read the list of \fI\%Breaking Changes\fP and consider their impact on your codebase. For your convenience, some upgrade notes have been included. .UNINDENT .UNINDENT .INDENT 0.0 .IP \(bu 2 New: Add capability to use references in schemas (Frank Sachsenheim). .IP \(bu 2 New: Support for binary type (Matthew Ellison). .IP \(bu 2 New: Allow callables for \(aqdefault\(aq schema rule (Dominik Kellner). .IP \(bu 2 New: Support arbitrary types with \(aqmax\(aq and \(aqmin\(aq (Frank Sachsenheim). .IP \(bu 2 New: Support any iterable with \(aqminlength\(aq and \(aqmaxlength\(aq. Closes \fI\%#158\fP\&. (Frank Sachsenheim) .IP \(bu 2 New: \(aqdefault\(aq normalization rule. Closes \fI\%#131\fP (Damián Nohales). .IP \(bu 2 New: \(aqexcludes\(aq rule (calve). Addresses \fI\%#132\fP\&. .IP \(bu 2 New: \(aqforbidden\(aq rule (Frank Sachsenheim). .IP \(bu 2 New: \(aqrename\(aq\-rule renames a field to a given value during normalization (Frank Sachsenheim). .IP \(bu 2 New: \(aqrename_handler\(aq\-rule that takes an callable that renames unknown fields (Frank Sachsenheim). .IP \(bu 2 New: \(aqValidator.purge_unknown\(aq\-property and conditional purging of unknown fields (Frank Sachsenheim). .IP \(bu 2 New: \(aqcoerce\(aq, \(aqrename_handler\(aq and \(aqvalidator\(aq can use class\-methods (Frank Sachsenheim). .IP \(bu 2 New: \(aq .nf * .fi of\(aq\-rules can be extended by concatenating another rule (Frank Sachsenheim). .IP \(bu 2 New: Allows various error output with error handlers (Frank Sachsenheim). .IP \(bu 2 New: Available rules etc. of a Validator\-instance are accessible as \(aqvalidation_rules\(aq, \(aqnormalization_rules\(aq, \(aqtypes\(aq, \(aqvalidators\(aq and \(aqcoercer\(aq \-property (Frank Sachsenheim). .IP \(bu 2 New: Custom rule\(aqs method docstrings can contain an expression to validate constraints for that rule when a schema is validated (Frank Sachsenheim). .IP \(bu 2 New: \(aqValidator.root_schema\(aq complements \(aqValidator.root_document\(aq (Frank Sachsenheim). .IP \(bu 2 New: \(aqValidator.document_path\(aq and \(aqValidator.schema_path\(aq properties can be used to determine the relation of the currently validating document to the \(aqroot_document\(aq / \(aqroot_schema\(aq (Frank Sachsenheim). .IP \(bu 2 New: Known, validated definition schemas are cached, thus validation run\-time of schemas is reduced (Frank Sachsenheim). .IP \(bu 2 New: Add testing with Docker (Frank Sachsenheim). .IP \(bu 2 New: Support CPython 3.5 (Frank Sachsenheim). .IP \(bu 2 Fix: \(aqallow_unknown\(aq inside .nf * .fi of rule is ignored. Closes \fI\%#251\fP\&. (Davis Kirkendall) .IP \(bu 2 Fix: unexpected TypeError when using allow_unknown in a schema defining a list of dicts. Closes \fI\%#250\fP\&. (Davis Kirkendall) .IP \(bu 2 Fix: validate with \(aqupdate=True\(aq does not work when required fields are in a list of subdicts (Jonathan Huot). .IP \(bu 2 Fix: \(aqnumber\(aq type fails if value is boolean. Closes \fI\%#144\fP\&. (Frank Sachsenheim). .IP \(bu 2 Fix: allow None in \(aqdefault\(aq normalization rule (Damián Nohales). .IP \(bu 2 Fix: in 0.9.2, coerce does not maintain proper nesting on dict fields. Closes \fI\%#185\fP\&. .IP \(bu 2 Fix: normalization not working for valueschema and propertyschema. Closes \fI\%#155\fP (Frank Sachsenheim). .IP \(bu 2 Fix: \(aqcoerce\(aq on List elements produces unexpected results. Closes \fI\%#161\fP\&. (Frank Sachsenheim) .IP \(bu 2 Fix: \(aqcoerce\(aq\-constraints are validated. (Frank Sachsenheim) .IP \(bu 2 Fix: Unknown fields are normalized. (Frank Sachsenheim) .IP \(bu 2 Fix: Dependency on boolean field now works as expected. Addresses \fI\%#138\fP\&. (Roman Redkovich) .IP \(bu 2 Fix: Add missing deprecation\-warnings. (Frank Sachsenheim) .IP \(bu 2 Docs: clarify read\-only rule. Closes \fI\%#127\fP\&. .IP \(bu 2 Docs: split Usage page into Usage; Validation Rules: Normalization Rules. (Frank Sachsenheim) .UNINDENT .SS Breaking Changes .sp Several relevant breaking changes have been introduced with this release. For the inside scoop, please see the upgrade notes\&. .INDENT 0.0 .IP \(bu 2 Change: \(aqerrors\(aq values are lists containing error messages. Previously, they were simple strings if single errors, lists otherwise. Closes \fI\%#210\fP\&. (Frank Sachsenheim) .IP \(bu 2 Change: Custom validator methods: remove the second argument. (Frank Sachsenheim) .IP \(bu 2 Change: Custom validator methods: invert the logic of the conditional clauses where is tested what a value is not / has not. (Frank Sachsenheim) .IP \(bu 2 Change: Custom validator methods: replace calls to \(aqself._error\(aq with \(aqreturn True\(aq, or False, or None. (Frank Sachsenheim) .IP \(bu 2 Change: Remove \(aqtransparent_schema_rule\(aq in favor of docstring schema validation. (Frank Sachsenheim) .IP \(bu 2 Change: Rename \(aqproperty_schema\(aq rule to \(aqkeyschema\(aq. (Frank Sachsenheim) .IP \(bu 2 Change: Replace \(aqvalidate_update\(aq method with \(aqupdate\(aq keywork argument. (Frank Sachsenheim) .IP \(bu 2 Change: The processed root\-document of is now available as \(aqroot_document\(aq\- property of the (child\-)Validator. (Frank Sachsenheim) .IP \(bu 2 Change: Removed \(aqcontext\(aq\-argument from \(aqvalidate\(aq\-method as this is set upon the creation of a child\-validator (Frank Sachsenheim). .IP \(bu 2 Change: \(aqValidationError\(aq\-exception renamed to \(aqDocumentError\(aq. (Frank Sachsenheim) .IP \(bu 2 Change: Consolidated all schema\-related error\-messages\(aq names. (Frank Sachsenheim) .IP \(bu 2 Change: Use warnings.warn for deprecation\-warnings if available. (Frank Sachsenheim) .UNINDENT .SS Version 0.9.2 .sp Released on September 23, 2015 .INDENT 0.0 .IP \(bu 2 Fix: don\(aqt rely on deepcopy since it can\(aqt properly handle complex objects in Python 2.6. .UNINDENT .SS Version 0.9.1 .sp Released on July 7 2015 .INDENT 0.0 .IP \(bu 2 Fix: \(aqrequired\(aq is always evaluated, independent of eventual missing dependencies. This changes the previous behaviour whereas a required field with dependencies would only be reported as missing if all dependencies were met. A missing required field will always be reported. Also see the discussion in \fI\%https://github.com/pyeve/eve/pull/665\fP\&. .UNINDENT .SS Version 0.9 .sp Released on June 24 2015. Codename: \(aqMastrolindo\(aq. .INDENT 0.0 .IP \(bu 2 New: \(aqoneof\(aq rule which provides a list of definitions in which only one should validate (C.D. Clark III). .IP \(bu 2 New: \(aqnoneof\(aq rule which provides a list of definitions that should all not validate (C.D. Clark III). .IP \(bu 2 New: \(aqanyof\(aq rule accepts a list of definitions and checks that one definition validates (C.D. Clark III). .IP \(bu 2 New: \(aqallof\(aq rule validates if if all definitions validate (C.D. Clark III). .IP \(bu 2 New: \(aqvalidator.validated\(aq takes a document as argument and returns a validated document or \(aqNone\(aq if validation failed (Frank Sachsenheim). .IP \(bu 2 New: PyPy support (Frank Sachsenheim). .IP \(bu 2 New: Type coercion (Brett). .IP \(bu 2 New: Added \(aqpropertyschema\(aq validation rule (Frank Sachsenheim). .IP \(bu 2 Change: Use \(aqstr.format\(aq in error messages so if someone wants to override them does not get an exception if arguments are not passed. Closes \fI\%#105\fP\&. (Brett) .IP \(bu 2 Change: \(aqkeyschema\(aq renamed to \(aqvalueschema\(aq, print a deprecation warning (Frank Sachsenheim). .IP \(bu 2 Change: \(aqtype\(aq can also be a list of types (Frank Sachsenheim). .IP \(bu 2 Fix: useages of \(aqdocument\(aq to \(aqself.document\(aq in \(aq_validate\(aq (Frank Sachsenheim). .IP \(bu 2 Fix: when \(aqitems\(aq is applied to a list, field name is used as key for \(aqvalidator.errors\(aq, and offending field indexes are used as keys for field errors ({\(aqa_list_of_strings\(aq: {1: \(aqnot a string\(aq}}) \(aqtype\(aq can be a list of valid types. .IP \(bu 2 Fix: Ensure that additional \fI**kwargs\fP of a subclass persist through validation (Frank Sachsenheim). .IP \(bu 2 Fix: improve failure message when testing against multiple types (Frank Sachsenheim). .IP \(bu 2 Fix: ignore \(aqkeyschema\(aq when not a mapping (Frank Sachsenheim). .IP \(bu 2 Fix: ignore \(aqschema\(aq when not a sequence (Frank Sachsenheim). .IP \(bu 2 Fix: allow_unknown can also be set for nested dicts. Closes \fI\%#75\fP\&. (Tobias Betz) .IP \(bu 2 Fix: raise SchemaError when an unallowed \(aqtype\(aq is used in conjunction with \(aqschema\(aq rule (Tobias Betz). .IP \(bu 2 Docs: added section that points out that YAML, JSON, etc. can be used to define schemas (C.D. Clark III). .IP \(bu 2 Docs: Improve \(aqallow_unknown\(aq documentation (Frank Sachsenheim). .UNINDENT .SS Version 0.8.1 .sp Released on Mar 16 2015. .INDENT 0.0 .IP \(bu 2 Fix: dependency on a sub\-document field does not work. Closes \fI\%#64\fP\&. .IP \(bu 2 Fix: readonly validation should happen before any other validation. Closes \fI\%#63\fP\&. .IP \(bu 2 Fix: allow_unknown does not apply to sub\-dictionaries in a list. Closes \fI\%#67\fP\&. .IP \(bu 2 Fix: two tests being ignored because of name typo. .IP \(bu 2 Fix: update mode does not ignore required fields in subdocuments. Closes \fI\%#72\fP\&. .IP \(bu 2 Fix: allow_unknown does not respect custom rules. Closes \fI\%#66\fP\&. .IP \(bu 2 Fix: typo in docstrings (Riccardo). .UNINDENT .SS Version 0.8 .sp Released on Jan 7 2015. .INDENT 0.0 .IP \(bu 2 \(aqdependencies\(aq also supports dependency values. .IP \(bu 2 \(aqallow_unknown\(aq can also be set to a validation schema, in which case unknown fields will be validated against it. Closes pyeve/eve:issue:\fI405\fP\&. .IP \(bu 2 New function\-based custom validation mode (Luo Peng). .IP \(bu 2 Fields with empty definitions in schema were reported as non\-existent. Now they are considered as valid, whatever their value is (Jaroslav Semančík). .IP \(bu 2 If dependencies are precised for a \(aqrequired\(aq field, then the presence of the field is only validated if all dependencies are present (Trong Hieu HA). .IP \(bu 2 Documentation typo (Nikita Vlaznev \fI\%#55\fP). .IP \(bu 2 [CI] Add travis_retry to pip install in case of network issues (Helgi Þormar Þorbjörnsson \fI\%#49\fP) .UNINDENT .SS Version 0.7.2 .sp Released on Jun 19 2014. .INDENT 0.0 .IP \(bu 2 Successfully validate int as float type (Florian Rathgeber). .UNINDENT .SS Version 0.7.1 .sp Released on Jun 17 2014. .INDENT 0.0 .IP \(bu 2 Validation schemas are now validated up\-front. When you pass a Schema to the Validator it will be validated against the supported ruleset (Paul Weaver). Closes \fI\%#39\fP\&. .IP \(bu 2 Custom validators also have access to a special \(aqself.document\(aq variable that allows validation of a field to happen in context of the rest of the document (Josh Villbrandt). .IP \(bu 2 Validator options like \(aqallow_unknown\(aq and \(aqignore_none_values\(aq are now taken into consideration when validating sub\-dictionaries. Closes \fI\%#40\fP\&. .UNINDENT .SS Version 0.7 .sp Released on May 16 2014. .INDENT 0.0 .IP \(bu 2 Python 3.4 is now supported. .IP \(bu 2 tox support. .IP \(bu 2 Added \(aqdependencies\(aq validation rule (Lujeni). .IP \(bu 2 Added \(aqkeyschema\(aq validation rule (Florian Rathgeber). .IP \(bu 2 Added \(aqregex\(aq validation rule. Closes \fI\%#29\fP\&. .IP \(bu 2 Added \(aqset\(aq as a core data type. Closes \fI\%#31\fP\&. .IP \(bu 2 Not\-nullable fields are validated independetly of their type definition (Jaroslav Semančík). .IP \(bu 2 Python trove classifiers added to setup.py. Closes \fI\%#32\fP\&. .IP \(bu 2 \(aqmin\(aq and \(aqmax\(aq now apply to floats and numbers too. Closes \fI\%#30\fP\&. .UNINDENT .SS Version 0.6 .sp Released on February 10 2014 .INDENT 0.0 .IP \(bu 2 Added \(aqnumber\(aq data type, which validates against both float and integer values (Brandon Aubie). .IP \(bu 2 Added support for running tests with py.test .IP \(bu 2 Fix non\-blocking problem introduced with 0.5 (Martin Ortbauer). .IP \(bu 2 Fix bug when _error() is calld twice for a field (Jaroslav Semančík). .IP \(bu 2 More precise error message in rule \(aqschema\(aq validation (Jaroslav Semančík). .IP \(bu 2 Use \(aqallowed\(aq field for integer just like for string (Peter Demin). .UNINDENT .SS Version 0.5 .sp Released on December 4 2013 .INDENT 0.0 .IP \(bu 2 \(aqvalidator.errors\(aq now returns a dictionary where keys are document fields and values are lists of validation errors for the field. .IP \(bu 2 Validator instances are now callable. Instead of \fIvalidated = validator.validate(document)\fP you can now choose to do \(aqvalidated = validator(document)\(aq (Eelke Hermens). .UNINDENT .SS Version 0.4.0 .sp Released on September 24 2013. .INDENT 0.0 .IP \(bu 2 \(aqvalidate_update\(aq is deprecated and will be removed with next release. Use \(aqvalidate\(aq with \(aqupdate=True\(aq instead. Closes \fI\%#21\fP\&. .IP \(bu 2 Fixed a minor encoding issue which made installing on Windows/Python3 impossible. Closes \fI\%#19\fP (Arsh Singh). .IP \(bu 2 Fix documentation typo (Daniele Pizzolli). .IP \(bu 2 \(aqtype\(aq validation is always performed first (only exception being \(aqnullable\(aq). On failure, subsequent rules on the same field are skipped. Closes \fI\%#18\fP\&. .UNINDENT .SS Version 0.3.0 .sp Released on July 9 2013. .INDENT 0.0 .IP \(bu 2 docstrings now conform to PEP8. .IP \(bu 2 \fIself.errors\fP returns an empty list if validate() has not been called. .IP \(bu 2 added validation for the \(aqfloat\(aq data type. .IP \(bu 2 \(aqnullable\(aq rule added to allow for null field values to be accepted in validations. This is different than required in that you can actively change a value to None instead of omitting or ignoring it. It is essentially the ignore_none_values, allowing for more fine grained control down to the field level (Kaleb Pomeroy). .UNINDENT .SS Version 0.2.0 .sp Released on April 18 2013. .INDENT 0.0 .IP \(bu 2 \(aqallow_unknown\(aq option added. .UNINDENT .SS Version 0.1.0 .sp Released on March 15 2013. Codename: \(aqClaw\(aq. .INDENT 0.0 .IP \(bu 2 entering beta phase. .IP \(bu 2 support for Python 3. .IP \(bu 2 pep8 and pyflakes fixes (Harro van der Klauw). .IP \(bu 2 removed superflous typecheck for empty validator (Harro van der Klauw). .IP \(bu 2 \(aqignore_none_values\(aq option to ignore None values when type checking (Harro van der Klauw). .IP \(bu 2 \(aqminlenght\(aq and \(aqmaxlength\(aq now apply to lists as well (Harro van der Klauw). .UNINDENT .SS Version 0.0.3 .sp Released on January 29 2013 .INDENT 0.0 .IP \(bu 2 when a list item fails, its offset is now returned along with the list name. .IP \(bu 2 \(aqtransparent_schema_rules\(aq option added. .IP \(bu 2 \(aqempty\(aq rule for string fields. .IP \(bu 2 \(aqschema\(aq rule on lists of arbitrary lenght (Martjin Vermaat). .IP \(bu 2 \(aqallowed\(aq rule on strings (Martjin Vermaat). .IP \(bu 2 \(aqitems\(aq (dict) is now deprecated. Use the upgraded \(aqschema\(aq rule instead. .IP \(bu 2 AUTHORS file added to sources. .IP \(bu 2 CHANGES file added to sources. .UNINDENT .SS Version 0.0.2 .sp Released on November 22 2012. .INDENT 0.0 .IP \(bu 2 Added support for addition and validation of custom data types. .IP \(bu 2 Several documentation improvements. .UNINDENT .SS Version 0.0.1 .sp Released on October 16 2012. .sp First public preview release. .SS Upgrading to Cerberus 1.0 .SS Major Additions .SS Error Handling .sp The inspection on and representation of errors is thoroughly overhauled and allows a more detailed and flexible handling. Make sure you have look on errors\&. .sp Also, \fBerrors\fP (as provided by the default \fBBasicErrorHandler\fP) values are lists containing error messages, and possibly a \fBdict\fP as last item containing nested errors. Previously, they were strings if single errors per field occured; lists otherwise. .SS Deprecations .SS \fBValidator\fP class .SS transparent_schema_rules .sp In the past you could override the schema validation by setting \fBtransparent_schema_rules\fP to \fBTrue\fP\&. Now all rules whose implementing method\(aqs docstring contain a schema to validate the arguments for that rule in the validation schema, are validated. To omit the schema validation for a particular rule, just omit that definition, but consider it a bad practice. The \fBValidator\fP\-attribute and \-initialization\-argument \fBtransparent_schema_rules\fP are removed without replacement. .SS validate_update .sp The method \fBvalidate_update\fP has been removed from \fBValidator\fP\&. Instead use \fBvalidate()\fP with the keyword\-argument \fBupdate\fP set to \fBTrue\fP\&. .SS Rules .SS items (for mappings) .sp The usage of the \fBitems\fP\-rule is restricted to sequences. If you still had schemas that used that rule to validate \fI\%mappings\fP, just rename these instances to \fBschema\fP (docs). .SS keyschema & valueschema .sp To reflect the common terms in the Pythoniverse [1], the rule for validating all \fIvalues\fP of a \fI\%mapping\fP was renamed from \fBkeyschema\fP to \fBvalueschema\fP (docs). Furthermore a rule was implemented to validate all \fIkeys\fP, introduced as \fBpropertyschema\fP, now renamed to \fBkeyschema\fP (docs). This means code using prior versions of cerberus would not break, but bring up wrong results! .sp To update your code you may adapt cerberus\(aq iteration: .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP 1. 3 Rename \fBkeyschema\fP to \fBvalueschema\fP in your schemas. (\fB0.9\fP) .IP 2. 3 Rename \fBpropertyschema\fP to \fBkeyschema\fP in your schemas. (\fB1.0\fP) .UNINDENT .UNINDENT .UNINDENT .INDENT 0.0 .TP .B Note that \fBpropertyschema\fP will \fInot\fP be handled as an alias like \fBkeyschema\fP was in the \fB0.9\fP\-branch. .UNINDENT .SS Custom validators .SS Data types .sp Since the \fBtype\fP\-rule allowed multiple arguments cerberus\(aq type validation code was somewhat cumbersome as it had to deal with the circumstance that each type checking method would file an error though another one may not \- and thus positively validate the constraint as a whole. The refactoring of the error handling allows cerberus\(aq type validation to be much more lightweight and to formulate the corresponding methods in a simpler way. .sp Previously such a method would test what a value \fIis not\fP and submit an error. Now a method tests what a value \fIis\fP to be expected and returns \fBTrue\fP in that case. .sp This is the most critical part of updating your code, but still easy when your head is clear. Of course your code is well tested. It\(aqs essentially these three steps. Search, Replace and Regex may come at your service. .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP 1. 3 Remove the second method\(aqs argument (probably named \fBfield\fP). .IP 2. 3 Invert the logic of the conditional clauses where is tested what a value is not / has not. .IP 3. 3 Replace calls to \fBself._error\fP below such clauses with \fBreturn True\fP\&. .UNINDENT .UNINDENT .UNINDENT .sp A method doesn\(aqt need to return \fBFalse\fP or any value when expected criteria are not met. .sp Here\(aqs the change from the documentation example. .sp pre\-1.0: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C def _validate_type_objectid(self, field, value): if not re.match(\(aq[a\-f0\-9]{24}\(aq, value): self._error(field, errors.BAD_TYPE) .ft P .fi .UNINDENT .UNINDENT .sp 1.0: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C def _validate_type_objectid(self, value): if re.match(\(aq[a\-f0\-9]{24}\(aq, value): return True .ft P .fi .UNINDENT .UNINDENT .IP [1] 5 compare \fI\%dictionary\fP .SS Authors .sp Cerberus is developed and maintained by the Cerberus community. It was created by Nicola Iarocci. .SS Core maintainers .INDENT 0.0 .IP \(bu 2 Nicola Iarocci (nicolaiarocci) .IP \(bu 2 Frank Sachsenheim (funkyfuture) .UNINDENT .SS Contributors .INDENT 0.0 .IP \(bu 2 Antoine Lubineau .IP \(bu 2 Arsh Singh .IP \(bu 2 Audric Schiltknecht .IP \(bu 2 Brandon Aubie .IP \(bu 2 Brett .IP \(bu 2 Bruno Oliveira .IP \(bu 2 Bryan W. Weber .IP \(bu 2 C.D. Clark III .IP \(bu 2 Christian Hogan .IP \(bu 2 Damián Nohales .IP \(bu 2 Danielle Pizzolli .IP \(bu 2 Davis Kirkendall .IP \(bu 2 Denis Carriere .IP \(bu 2 Dominik Kellner .IP \(bu 2 Eelke Hermens .IP \(bu 2 Florian Rathgeber .IP \(bu 2 Gabriel Wainer .IP \(bu 2 Harro van der Klauw .IP \(bu 2 Jaroslav Semančík .IP \(bu 2 Jonathan Huot .IP \(bu 2 Kaleb Pomeroy .IP \(bu 2 Kirill Pavlov .IP \(bu 2 Kornelijus Survila .IP \(bu 2 Lujeni .IP \(bu 2 Luo Peng .IP \(bu 2 Martijn Vermaat .IP \(bu 2 Martin Ortbauer .IP \(bu 2 Matthew Ellison .IP \(bu 2 Michael Klich .IP \(bu 2 Nikita Vlaznev .IP \(bu 2 Paul Weaver .IP \(bu 2 Peter Demin .IP \(bu 2 Riccardo .IP \(bu 2 Roman Redkovich .IP \(bu 2 Sebastian Rajo .IP \(bu 2 Sergey Leshchenko .IP \(bu 2 Tobias Betz .IP \(bu 2 Trong Hieu HA .IP \(bu 2 Waldir Pimenta .IP \(bu 2 calve .IP \(bu 2 gilbsgilbs .UNINDENT .sp A full, up\-to\-date list of contributors is available from git with: .INDENT 0.0 .INDENT 3.5 git shortlog \-sne .UNINDENT .UNINDENT .SS Contact .sp If you’ve scoured the prose and API documentation and still can’t find an answer to your question, below are various support resources that should help. We do request that you do at least skim the documentation before posting tickets or mailing list questions, however! .sp If you\(aqd like to stay up to date on the community and development of Cerberus, there are several options: .SS Blog .sp New releases are usually announced on \fI\%my Website\fP\&. .SS Twitter .sp I often tweet about new features and releases of Cerberus. Follow \fI\%@nicolaiarocci\fP\&. .SS Mailing List .sp The \fI\%mailing list\fP is intended to be a low traffic resource for users, developers and contributors of both the Cerberus and Eve projects. .SS Issues tracker .sp To file new bugs or search existing ones, you may visit \fI\%Issues\fP page. This does require a (free and easy to set up) GitHub account. .SS GitHub repository .sp Of course the best way to track the development of Cerberus is through the \fI\%GitHub repo\fP\&. .SS License .sp Cerberus is an open source project by \fI\%Nicola Iarocci\fP\&. .sp ISC License .sp Copyright (c) 2012\-2016 Nicola Iarocci. .sp Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. .sp THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. .SH COPYRIGHT NOTICE .sp Cerberus is an open source project by \fI\%Nicola Iarocci\fP\&. See the original \fI\%LICENSE\fP for more information. .SH AUTHOR Nicola Iarocci .SH COPYRIGHT 2012-2019, Nicola Iarocci .\" Generated by docutils manpage writer. .