Colander API¶
Exceptions¶
- class colander.Invalid(node, msg=None, value=None)¶
Raised by data types / validators
Raised if the value for a particular node is not valid.
The constructor receives a mandatory
node
argument. This must be an instance of thecolander.SchemaNode
class, or at least something with the same interface.The constructor also receives an optional
msg
keyword argument, defaulting toNone
. Themsg
argument is a freeform field indicating the error circumstance.The constructor additionally may receive an optional
value
keyword, indicating the value related to the error.- pos¶
An integer representing the position of this exception's schema node relative to all other child nodes of this exception's parent schema node. For example, if this exception is related to the third child node of its parent's schema,
pos
might be the integer3
.pos
may also beNone
, in which case this exception is the root exception.
- children¶
A list of child exceptions. Each element in this list (if any) will also be an
colander.Invalid
exception, recursively, representing the error circumstances for a particular schema deserialization.
- msg¶
A
str
orunicode
object, or a translation string instance representing a freeform error value set by a particular type during an unsuccessful deserialization. If this exception is only structural (only exists to be a parent to some inner child exception), this value will beNone
.
- node¶
The schema node to which this exception relates.
- value¶
An attribute not used internally by Colander, but which can be used by higher-level systems to attach arbitrary values to Colander exception nodes. For example, In the system named Deform, which uses Colander schemas to define HTML form renderings, the
value
is used when raising an exception from a widget as the value which should be redisplayed when an error is shown.
- add(exc, pos=None)¶
Add a child exception to the list of children for this exception.
exc
must be an instance ofcolander.Invalid
or a subclass.pos
is a value important for accurate error reporting.If it is provided, it must be an integer representing the position of
exc
relative to all other subexceptions of this exception node. For example, if the exception being added is about the third child of the exception which isself
,pos
might be passed as3
.If
pos
is provided, it will be assigned to thepos
attribute of the providedexc
object.
- asdict(translate=None, separator='; ')¶
Return a dict holding a basic error report for this exception.
The values in the dict will not be language-translated by default.
If
translate
is supplied, it must be a callable taking a translation string as its sole argument and returning a localized, interpolated string. If so, the values in returned dict will be language-translated.If
separator
is supplied, error messages are joined with that.
- messages()¶
Return an iterable of error messages for this exception.
Uses the
msg
attribute of this error node.If the
msg
attribute is iterable, return it.If it is not iterable, and is non-
None
, return a single-element list containing themsg
value.If the value is
None
, an empty list is returned.
- paths()¶
A generator yielding each path through the exception graph.
Each yielded path is represented as a tuple of exception nodes.
Within each tuple, the leftmost item will represent the root schema node, the rightmost item will represent the leaf schema node.
- class colander.UnsupportedFields(node, fields, msg=None)¶
Raised by a mapping schema which finds unknown fields cstruct.
- fields¶
The
dict
with all detected extra fields and their values.Nodes that contain extra fields can be located by the position of this exception in the exception tree hierarchy.
- class colander.UnboundDeferredError¶
Raised by
SchemaNode.deserialize()
Raised when an attempt is made to deserialize a node which has an unbound
deferred
validator.
Validators¶
- class colander.All(*validators)¶
Composite validator
Succeeds if none of its subvalidators raises
colander.Invalid
.
- class colander.Any(*validators)¶
Composite validator
Succeeds if at least one of its subvalidators does not raise
colander.Invalid
.
- class colander.Range(min=None, max=None, min_err='${val} is less than minimum value ${min}', max_err='${val} is greater than maximum value ${max}')¶
Enforces that a value lies within a given range.
Raises if the value it is less than
min
or greater thanmax
.If
min
is not specified, or is specified asNone
, no lower bound is checked.If
max
is not specified, or is specified asNone
, no upper bound is checked.
min_err
is used to form themsg
of thecolander.Invalid
error when reporting a validation failure where the value is less than minimum. Ifmin_err
is specified, it must be a string. The string may contain the replacement targets${min}
and${val}
, representing the minimum value and the provided value respectively. If not provided,min_err
defaults to'${val} is less than minimum value ${min}'
.
max_err
is used to form themsg
of thecolander.Invalid
error when reporting a validation failure where the value exceeds the maximum. Ifmax_err
is specified, it must be a string. The string may contain the replacement targets${max}
and${val}
, representing the maximum value and the provided value respectively. If it is not provided, it defaults to'${val} is greater than maximum value ${max}'
.
- class colander.Length(min=None, max=None, min_err='Shorter than minimum length ${min}', max_err='Longer than maximum length ${max}')¶
Enforces that the length of a value falls within a given range.
Raises if the value's length does not fall within the range described by the supplied
min
andmax
arguments.The value can be any sequence, most often a string.
If
min
is not specified, or is specified asNone
, no lower bound on the length is checked.If
max
is not specified, or is specified asNone
, no upper bound on the length is checked.The default error messages are "Shorter than minimum length ${min}" and "Longer than maximum length ${max}". These can be customized:
min_err
is used to form themsg
of thecolander.Invalid
error when reporting a validation failure where the value's length is less thanmin
. Ifmin_err
is specified, it must be a string. The string may contain the replacement target${min}
.
max_err
is used to form themsg
of thecolander.Invalid
error when reporting a validation failure where the value's length is greater thanmax
. Ifmax_err
is specified, it must be a string. The string may contain the replacement target${max}
.
- class colander.OneOf(choices, msg_err='"${val}" is not one of ${choices}')¶
Enforces that a value is one of a fixed set of values.
msg_err
is used to form themsg
of thecolander.Invalid
error when reporting a validation failure. Ifmsg_err
is specified, it must be a string. The string may contain the replacement targets${choices}
and${val}
, representing the set of forbidden values and the provided value respectively.
- class colander.NoneOf(choices, msg_err='"${val}" must not be one of ${choices}')¶
Enforces that a value is not one of a fixed set of values.
msg_err
is used to form themsg
of thecolander.Invalid
error when reporting a validation failure. Ifmsg_err
is specified, it must be a string. The string may contain the replacement targets${choices}
and${val}
, representing the set of forbidden values and the provided value respectively.
- class colander.ContainsOnly(choices)¶
Enforces that each element in a sequence value is one of a fixeed set.
Useful when attached to a schemanode with, e.g., a
colander.Set
or another sequencetype.
- class colander.Function(function, msg=None, message=None)¶
Validator accepting a function and an optional message.
function
is called withvalue
during validation.If
function
returns anything falsey (None
,False
, the empty string,0
, an object with a__nonzero__
that returnsFalse
, etc.), raisecolander.Invalid
(validation fails);The
msg
of the raised exception will be the value of themsg
argument passed to this class' constructor.If
function
returns astr
object that is not the empty string, raisecolander.Invalid
using the string value returned from the function as the exception message (validation fails).If
function
returns anything which is truthy except a string object (e.g.,True
, the integer1
, an object with a__nonzero__
that returnsTrue
, etc), do not raisecolander.Invalid
(validation succeeds).The default value for the
msg
when not provided via the constructor isInvalid value
.The
message
parameter is deprecated: usemsg
instead.
- class colander.Regex(regex, msg=None, flags=0)¶
Regular expression validator.
regex
is a regular expression pattern that will be compiled and matched againstvalue
when validator is called.The compiled regex uses Python's
re.match()
, which only matches at the beginning of the string and not at the beginning of each line.To match the entire string, enclose the regular expression with
^
and$
.If
msg
is supplied, it will be the error message to be used; otherwise, defaults to 'String does not match expected pattern'.The
regex
expression behaviour can be modified by specifying anyflags
value taken byre.compile
.The
regex
argument may also be a pattern object (the result ofre.compile
) instead of a string.When called with
value
matching the regular expression, no exception is raised (validation succeeds);If
value
does not match the regular expression, raisescolander.Invalid
with themsg
error message.
- class colander.Email(msg=None)¶
Email address validator.
If
msg
is supplied, it will be the error message to be used when raisingcolander.Invalid
; otherwise, defaults to 'Invalid email address'.
- class colander.DataURL(url_err='Not a data URL', mimetype_err='Invalid MIME type', base64_err='Invalid Base64 encoded data')¶
Data URL validator.
If
url_msg
is supplied, it will be the error message to be used when raisingcolander.Invalid
for a syntactically incorrect data URL, defaults to 'Not a data URL'.If, however, the data URL string is syntactically correct but contains an invalid MIME type, uses the supplied
mimetype_err
message (defaults to Invalid MIME type')If the data URL string is an incorrectly encoded Base64 value, passes the uses the supplied
base64_err
message (defaults to 'Invalid Base64 encoded data').
- colander.luhnok(node, value)¶
Enforces that the value passes a luhn mod-10 checksum (credit cards).
value
must be a string, not an integer.
- colander.url¶
A validator which ensures the value is a URL (via regex).
- colander.uuid¶
A UUID hexadecimal string validator via regular expression using
colander.Regex
.
Types¶
- class colander.Mapping(unknown='ignore')¶
A type which represents a mapping of names to nodes.
The subnodes of the
colander.SchemaNode
that wraps this type imply the named keys and values in the mapping.The constructor of this type accepts one extra optional keyword argument that other types do not:
unknown
. An attribute of the same name can be set on a type instance to control the behavior after construction.
- unknown
unknown
controls the behavior of this type when an unknown key is encountered in the cstruct passed to thedeserialize
method of this instance. All the potential values ofunknown
are strings. They are:
ignore
means that keys that are not present in the schema associated with this type will be ignored during deserialization.
raise
will cause acolander.Invalid
exception to be raised when unknown keys are present in the cstruct during deserialization.
preserve
will preserve the 'raw' unknown keys and values in the appstruct returned by deserialization.Default:
ignore
.Special behavior is exhibited when a subvalue of a mapping is present in the schema but is missing from the mapping passed to either the
serialize
ordeserialize
method of this class. In this case, thecolander.null
value will be passed to theserialize
ordeserialize
method of the schema node representing the subvalue of the mapping respectively. During serialization, this will result in the behavior described in Serializing The Null Value for the subnode. During deserialization, this will result in the behavior described in Deserializing The Null Value for the subnode.If the
colander.null
value is passed to the serialize method of this class, a dictionary will be returned, where each of the values in the returned dictionary is the serialized representation of the null value for its type.
- class colander.Tuple¶
A type which represents a fixed-length sequence of nodes.
The subnodes of the
colander.SchemaNode
that wraps this type imply the positional elements of the tuple in the order they are added.This type is willing to serialize and deserialized iterables that, when converted to a tuple, have the same number of elements as the number of the associated node's subnodes.
If the
colander.null
value is passed to the serialize method of this class, thecolander.null
value will be returned.
- class colander.Set¶
A type representing a non-overlapping set of items. Deserializes an iterable to a
set
object.If the
colander.null
value is passed to the serialize method of this class, thecolander.null
value will be returned.
- class colander.List¶
Type representing an ordered sequence of items.
Deserializes an iterable to a
list
object.If the
colander.null
value is passed to the serialize method of this class, thecolander.null
value will be returned.
- class colander.Sequence(accept_scalar=False)¶
A type which represents a variable-length sequence of nodes, all of which must be of the same type.
The type of the first subnode of the
colander.SchemaNode
that wraps this type is considered the sequence type.The optional
accept_scalar
argument to this type's constructor indicates what should happen if the value found during serialization or deserialization does not have an__iter__
method or is a mapping type.If
accept_scalar
isTrue
and the value does not have an__iter__
method or is a mapping type, the value will be turned into a single element list.If
accept_scalar
isFalse
and the value does not have an__iter__
method or is a mapping type, ancolander.Invalid
error will be raised during serialization and deserialization.The default value of
accept_scalar
isFalse
.If the
colander.null
value is passed to the serialize method of this class, thecolander.null
value is returned.
- class colander.String(encoding=None, allow_empty=False)¶
A type representing a text string.
It is always an error to deserialize a non-text/binary type. Binary types are only accepted if the
encoding
argument is specified.This type constructor accepts two arguments:
encoding
Represents the encoding which should be applied to value serialization and deserialization, for example
utf-8
. Ifencoding
is passed asNone
, theserialize
method of this type will not do any special encoding of the appstruct it is provided, nor will thedeserialize
method of this type do any special decoding of the cstruct it is provided; inputs and outputs will be assumed to be text.encoding
defaults toNone
.If
encoding
isNone
:
Any value to
serialize
is run through thestr
function to convert to text, and the result is returned.A text input value to
deserialize
is returned untouched.If
encoding
is notNone
:
Any value to
serialize
is run through thestr
function to convert to text. The value is then encoded to binary with the encoding parameter (bytes(value, encoding)
) and the result (abytes
object) is returned.A text input value to
deserialize
is returned untouched.A binary input value to
deserialize
is decoded to text using the encoding parameter (str(value, encoding)
) and the result is returned.A corollary: If a
bytes
(as opposed to astr
object) is provided as a value to either the serialize or deserialize method of this type, and the type also has an non-None
encoding
, the string must be encoded with the type's encoding. If this is not true, ancolander.Invalid
error will result.allow_empty
Boolean, if True allows deserialization of an empty string. If False (default), empty strings will deserialize to
colander.null
The subnodes of the
colander.SchemaNode
that wraps this type are ignored.
- class colander.Integer(strict=False)¶
A type representing an integer.
If the
colander.null
value is passed to the serialize method of this class, thecolander.null
value will be returned.The Integer constructor takes an optional argument
strict
, which if enabled will verify that the number passed to serialize/deserialize is an integer, and not a float that would get truncated.The subnodes of the
colander.SchemaNode
that wraps this type are ignored.
- class colander.Float¶
A type representing a float.
If the
colander.null
value is passed to the serialize method of this class, thecolander.null
value will be returned.The subnodes of the
colander.SchemaNode
that wraps this type are ignored.
- class colander.Decimal(quant=None, rounding=None, normalize=False)¶
A type representing a decimal floating point. Deserialization returns an instance of the Python
decimal.Decimal
type.If the
colander.null
value is passed to the serialize method of this class, thecolander.null
value will be returned.The Decimal constructor takes three optional arguments,
quant
,rounding
andnormalize
. If supplied,quant
should be a string, (e.g.1.00
). If supplied,rounding
should be one of the Pythondecimal
module rounding options (e.g.decimal.ROUND_UP
,decimal.ROUND_DOWN
, etc). The serialized and deserialized result will be quantized and rounded viaresult.quantize(decimal.Decimal(quant), rounding)
.rounding
is ignored ifquant
is not supplied. Ifnormalize
isTrue
, the serialized and deserialized result will be normalized by stripping the rightmost trailing zeros.The subnodes of the
colander.SchemaNode
that wraps this type are ignored.
- class colander.Boolean(false_choices=('false', '0'), true_choices=(), false_val='false', true_val='true')¶
A type representing a boolean object.
The constructor accepts these keyword arguments:
false_choices
: The set of strings representing aFalse
value on deserialization.
true_choices
: The set of strings representing aTrue
value on deserialization.
false_val
: The value returned on serialization of a False value.
true_val
: The value returned on serialization of a True value.During deserialization, a value contained in
false_choices
, will be consideredFalse
.The behaviour for values not contained in
false_choices
depends ontrue_choices
: if it's empty, any value is consideredTrue
; otherwise, only values contained intrue_choices
are consideredTrue
, and an Invalid exception would be raised for values outside of bothfalse_choices
andtrue_choices
.Serialization will produce
true_val
orfalse_val
based on the value.If the
colander.null
value is passed to the serialize method of this class, thecolander.null
value will be returned.The subnodes of the
colander.SchemaNode
that wraps this type are ignored.
- class colander.GlobalObject(package)¶
A type representing an importable Python object. This type serializes 'global' Python objects (objects which can be imported) to dotted Python names.
Two dotted name styles are supported during deserialization:
pkg_resources
-style dotted names where non-module attributes of a module are separated from the rest of the path using a ':' e.g.package.module:attr
.
zope.dottedname
-style dotted names where non-module attributes of a module are separated from the rest of the path using a '.' e.g.package.module.attr
.These styles can be used interchangeably. If the serialization contains a
:
(colon), thepkg_resources
resolution mechanism will be chosen, otherwise thezope.dottedname
resolution mechanism will be chosen.The constructor accepts a single argument named
package
which should be a Python module or package object; it is used when relative dotted names are supplied to thedeserialize
method. A serialization which has a.
(dot) or:
(colon) as its first character is treated as relative. E.g. if.minidom
is supplied todeserialize
, and thepackage
argument to this type was passed thexml
module object, the resulting import would be forxml.minidom
. If a relative package name is supplied todeserialize
, and nopackage
was supplied to the constructor, ancolander.Invalid
error will be raised.If the
colander.null
value is passed to the serialize method of this class, thecolander.null
value will be returned.The subnodes of the
colander.SchemaNode
that wraps this type are ignored.
- class colander.DateTime(default_tzinfo=datetime.timezone.utc, format=None)¶
A type representing a Python
datetime.datetime
object.This type serializes python
datetime.datetime
objects to a ISO8601 string format. The format includes the date, the time, and the timezone of the datetime.The constructor accepts an argument named
default_tzinfo
which should be a Pythontzinfo
object. Ifdefault_tzinfo
is not specified the default tzinfo will be equivalent to UTC (Zulu time). Thedefault_tzinfo
tzinfo object is used to convert 'naive' datetimes to a timezone-aware representation during serialization. Ifdefault_tzinfo
is explicitly set toNone
then no default tzinfo will be applied to naive datetimes.You can adjust the error message reported by this class by changing its
err_template
attribute in a subclass on an instance of this class. By default, theerr_template
attribute is the stringInvalid date
. This string is used as the interpolation subject of a dictionary composed ofval
anderr
.val
anderr
are the unvalidatable value and the exception caused trying to convert the value, respectively. These may be used in an overridden err_template as${val}
and${err}
respectively as necessary, e.g._('${val} cannot be parsed as an iso8601 date: ${err}')
.For convenience, this type is also willing to coerce
datetime.date
objects to a DateTime ISO string representation during serialization. It does so by using midnight of the day as the time, and uses thedefault_tzinfo
to give the serialization a timezone.Likewise, for convenience, during deserialization, this type will convert
YYYY-MM-DD
ISO8601 values to a datetime object. It does so by using midnight of the day as the time, and uses thedefault_tzinfo
to give the serialization a timezone.If the
colander.null
value is passed to the serialize method of this class, thecolander.null
value will be returned.The subnodes of the
colander.SchemaNode
that wraps this type are ignored.
- class colander.Date(format=None)¶
A type representing a Python
datetime.date
object.This type serializes python
datetime.date
objects to a ISO8601 string format. The format includes the date only.The constructor accepts no arguments.
You can adjust the error message reported by this class by changing its
err_template
attribute in a subclass on an instance of this class. By default, theerr_template
attribute is the stringInvalid date
. This string is used as the interpolation subject of a dictionary composed ofval
anderr
.val
anderr
are the unvalidatable value and the exception caused trying to convert the value, respectively. These may be used in an overridden err_template as${val}
and${err}
respectively as necessary, e.g._('${val} cannot be parsed as an iso8601 date: ${err}')
.For convenience, this type is also willing to coerce
datetime.datetime
objects to a date-only ISO string representation during serialization. It does so by stripping off any time information, converting thedatetime.datetime
into a date before serializing.Likewise, for convenience, this type is also willing to coerce ISO representations that contain time info into a
datetime.date
object during deserialization. It does so by throwing away any time information related to the serialized value during deserialization.If the
colander.null
value is passed to the serialize method of this class, thecolander.null
value will be returned.The subnodes of the
colander.SchemaNode
that wraps this type are ignored.
- class colander.Time¶
A type representing a Python
datetime.time
object.Note
This type is new as of Colander 0.9.3.
This type serializes python
datetime.time
objects to a ISO8601 string format. The format includes the time only.The constructor accepts no arguments.
You can adjust the error message reported by this class by changing its
err_template
attribute in a subclass on an instance of this class. By default, theerr_template
attribute is the stringInvalid date
. This string is used as the interpolation subject of a dictionary composed ofval
anderr
.val
anderr
are the unvalidatable value and the exception caused trying to convert the value, respectively. These may be used in an overridden err_template as${val}
and${err}
respectively as necessary, e.g._('${val} cannot be parsed as an iso8601 date: ${err}')
.For convenience, this type is also willing to coerce
datetime.datetime
objects to a time-only ISO string representation during serialization. It does so by stripping off any date information, converting thedatetime.datetime
into a time before serializing.Likewise, for convenience, this type is also willing to coerce ISO representations that contain time info into a
datetime.time
object during deserialization. It does so by throwing away any date information related to the serialized value during deserialization.If the
colander.null
value is passed to the serialize method of this class, thecolander.null
value will be returned.The subnodes of the
colander.SchemaNode
that wraps this type are ignored.
- class colander.Enum(enum_cls, attr=None, typ=None)¶
A type representing a Python
enum.Enum
object.The constructor accepts three arguments named
enum_cls
,attr
, andtyp
.
enum_cls
is a mandatory argument and it should be a subclass ofenum.Enum
. This argument represents the appstruct's type.
attr
is an optional argument. Its default isname
. It is used to pick a serialized value from an enum instance. A serialized value must be unique.
typ
is an optional argument, and it should be an instance ofcolander.SchemaType
. This argument represents the cstruct's type. Iftyp
is not specified, a plaincolander.String
is used.