Decorators¶
Decorators for registering schema pre-processing and post-processing methods.
These should be imported from the top-level marshmallow module.
Methods decorated with
pre_load, post_load,
pre_dump, post_dump,
and validates_schema receive
many as a keyword argument. In addition, pre_load,
post_load,
and validates_schema receive
partial. If you don’t need these arguments, add **kwargs to your method
signature.
Example:
from marshmallow import (
Schema,
pre_load,
pre_dump,
post_load,
validates_schema,
validates,
fields,
ValidationError,
)
class UserSchema(Schema):
email = fields.Str(required=True)
age = fields.Integer(required=True)
@post_load
def lowerstrip_email(self, item, many, **kwargs):
item["email"] = item["email"].lower().strip()
return item
@pre_load(pass_collection=True)
def remove_envelope(self, data, many, **kwargs):
namespace = "results" if many else "result"
return data[namespace]
@post_dump(pass_collection=True)
def add_envelope(self, data, many, **kwargs):
namespace = "results" if many else "result"
return {namespace: data}
@validates_schema
def validate_email(self, data, **kwargs):
if len(data["email"]) < 3:
raise ValidationError("Email must be more than 3 characters", "email")
@validates("age")
def validate_age(self, data, **kwargs):
if data < 14:
raise ValidationError("Too young!")
Note
These decorators only work with instance methods. Class and static methods are not supported.
Warning
The invocation order of decorated methods of the same type is not guaranteed. If you need to guarantee order of different processing steps, you should put them in the same processing method.
Functions:
Register a method to invoke after serializing an object. |
|
Register a method to invoke after deserializing an object. |
|
Register a method to invoke before serializing an object. |
|
Register a method to invoke before deserializing an object. |
|
Mark decorated function as a hook to be picked up later. |
|
Register a validator method for field(s). |
|
Register a schema-level validator. |
- marshmallow.decorators.post_dump(fn=None, *, pass_collection=False, pass_original=False)[source]¶
Register a method to invoke after serializing an object. The method receives the serialized object and returns the processed object.
By default it receives a single object at a time, transparently handling the
manyargument passed to theSchema’sdump()call. Ifpass_collection=True, the raw data (which may be a collection) is passed.If
pass_original=True, the original data (before serializing) will be passed as an additional argument to the method.Changed in version 3.0.0:
manyis always passed as a keyword arguments to the decorated method.Changed in version 4.0.0:
pass_manyis renamed topass_collection.Changed in version 4.0.0:
pass_collectionandpass_originalare keyword-only arguments.- Parameters:
fn (Callable[[...], Any] | None)
pass_collection (bool)
pass_original (bool)
- Return type:
Callable[[…], Any]
- marshmallow.decorators.post_load(fn=None, *, pass_collection=False, pass_original=False)[source]¶
Register a method to invoke after deserializing an object. The method receives the deserialized data and returns the processed data.
By default it receives a single object at a time, transparently handling the
manyargument passed to theSchema’sload()call. Ifpass_collection=True, the raw data (which may be a collection) is passed.If
pass_original=True, the original data (before deserializing) will be passed as an additional argument to the method.Changed in version 3.0.0:
partialandmanyare always passed as keyword arguments to the decorated method.Changed in version 4.0.0:
pass_manyis renamed topass_collection.Changed in version 4.0.0:
pass_collectionandpass_originalare keyword-only arguments.Changed in version 4.0.0:
unknownis passed as a keyword argument to the decorated method.- Parameters:
fn (Callable[[...], Any] | None)
pass_collection (bool)
pass_original (bool)
- Return type:
Callable[[…], Any]
- marshmallow.decorators.pre_dump(fn=None, *, pass_collection=False)[source]¶
Register a method to invoke before serializing an object. The method receives the object to be serialized and returns the processed object.
By default it receives a single object at a time, transparently handling the
manyargument passed to theSchema’sdump()call. Ifpass_collection=True, the raw data (which may be a collection) is passed.Changed in version 3.0.0:
manyis always passed as a keyword arguments to the decorated method.Changed in version 4.0.0:
pass_manyis renamed topass_collection.Changed in version 4.0.0:
pass_collectionis a keyword-only argument.- Parameters:
fn (Callable[[...], Any] | None)
pass_collection (bool)
- Return type:
Callable[[…], Any]
- marshmallow.decorators.pre_load(fn=None, *, pass_collection=False)[source]¶
Register a method to invoke before deserializing an object. The method receives the data to be deserialized and returns the processed data.
By default it receives a single object at a time, transparently handling the
manyargument passed to theSchema’sload()call. Ifpass_collection=True, the raw data (which may be a collection) is passed.Changed in version 3.0.0:
partialandmanyare always passed as keyword arguments to the decorated method.Changed in version 4.0.0:
pass_manyis renamed topass_collection.Changed in version 4.0.0:
pass_collectionis a keyword-only argument.Changed in version 4.0.0:
unknownis passed as a keyword argument to the decorated method.- Parameters:
fn (Callable[[...], Any] | None)
pass_collection (bool)
- Return type:
Callable[[…], Any]
- marshmallow.decorators.set_hook(fn, tag, *, many=False, **kwargs)[source]¶
Mark decorated function as a hook to be picked up later. You should not need to use this method directly.
Note
Currently only works with functions and instance methods. Class and static methods are not supported.
- Returns:
Decorated function if supplied, else this decorator with its args bound.
- Parameters:
fn (Callable[[...], Any] | None)
tag (str)
many (bool)
kwargs (Any)
- Return type:
Callable[[…], Any]
- marshmallow.decorators.validates(*field_names)[source]¶
Register a validator method for field(s).
- Parameters:
field_names (str) – Names of the fields that the method validates.
- Return type:
Callable[[…], Any]
Changed in version 4.0.0: Accepts multiple field names as positional arguments.
Changed in version 4.0.0: Decorated methods receive
data_keyas a keyword argument.
- marshmallow.decorators.validates_schema(fn=None, *, pass_collection=False, pass_original=False, skip_on_field_errors=True)[source]¶
Register a schema-level validator.
By default it receives a single object at a time, transparently handling the
manyargument passed to theSchema’svalidate()call. Ifpass_collection=True, the raw data (which may be a collection) is passed.If
pass_original=True, the original data (before unmarshalling) will be passed as an additional argument to the method.If
skip_on_field_errors=True, this validation method will be skipped whenever validation errors have been detected when validating fields.Changed in version 3.0.0b1:
skip_on_field_errorsdefaults toTrue.Changed in version 3.0.0:
partialandmanyare always passed as keyword arguments to the decorated method.Changed in version 4.0.0:
unknownis passed as a keyword argument to the decorated method.Changed in version 4.0.0:
pass_manyis renamed topass_collection.Changed in version 4.0.0:
pass_collection,pass_original, andskip_on_field_errorsare keyword-only arguments.- Parameters:
fn (Callable[[...], Any] | None)
pass_collection (bool)
pass_original (bool)
skip_on_field_errors (bool)
- Return type:
Callable[[…], Any]