app.serializers.user
Description
Classes
|
|
|
|
|
- class app.serializers.user.UserExportWordSerializer(*, only: Optional[Union[Sequence[str], Set[str]]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)
- class Meta
Options object for a Schema.
Example usage:
class Meta: fields = ("id", "email", "date_created") exclude = ("password", "secret_attribute")
Available options:
fields
: Tuple or list of fields to include in the serialized result.additional
: Tuple or list of fields to include in addition to theexplicitly declared fields.
additional
andfields
are mutually-exclusive options.
include
: Dictionary of additional fields to include in the schema. It isusually better to define fields as class variables, but you may need to use this option, e.g., if your fields are Python keywords. May be an OrderedDict.
exclude
: Tuple or list of fields to exclude in the serialized result.Nested fields can be represented with dot delimiters.
dateformat
: Default format for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.timeformat
: Default format for Time <fields.Time> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, errors dictionaries will include the indexof invalid items in a collection.
load_only
: Tuple or list of fields to exclude from serialized results.dump_only
: Tuple or list of fields to exclude from deserializationunknown
: Whether to exclude, include, or raise an error for unknownfields in the data. Use EXCLUDE, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS
alias of
marshmallow.schema.SchemaOpts
- TYPE_MAPPING = {<class 'str'>: <class 'marshmallow.fields.String'>, <class 'bytes'>: <class 'marshmallow.fields.String'>, <class 'datetime.datetime'>: <class 'marshmallow.fields.DateTime'>, <class 'float'>: <class 'marshmallow.fields.Float'>, <class 'bool'>: <class 'marshmallow.fields.Boolean'>, <class 'tuple'>: <class 'marshmallow.fields.Raw'>, <class 'list'>: <class 'marshmallow.fields.Raw'>, <class 'set'>: <class 'marshmallow.fields.Raw'>, <class 'int'>: <class 'marshmallow.fields.Integer'>, <class 'uuid.UUID'>: <class 'marshmallow.fields.UUID'>, <class 'datetime.time'>: <class 'marshmallow.fields.Time'>, <class 'datetime.date'>: <class 'marshmallow.fields.Date'>, <class 'datetime.timedelta'>: <class 'marshmallow.fields.TimeDelta'>, <class 'decimal.Decimal'>: <class 'marshmallow.fields.Decimal'>}
- _bind_field(field_name: str, field_obj: marshmallow.fields.Field) None
Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was specified in
class Meta
.
- static _call_and_store(getter_func, data, *, field_name, error_store, index=None)
Call
getter_func
withdata
as its argument, and store any ValidationErrors.- Parameters
getter_func (callable) – Function for getting the serialized/deserialized value from
data
.data – The data passed to
getter_func
.field_name (str) – Field name.
index (int) – Index of the item being validated, if validating a collection, otherwise None.
- _declared_fields = {'to_pdf': <fields.Integer(dump_default=<marshmallow.missing>, attribute=None, validate=<OneOf(choices=[1, 0], labels=[], error='Must be one of: {choices}.')>, required=False, load_only=False, dump_only=False, load_default=<marshmallow.missing>, allow_none=False, error_messages={'required': 'Missing data for required field.', 'null': 'Field may not be null.', 'validator_failed': 'Invalid value.', 'invalid': 'Not a valid integer.', 'too_large': 'Number too large.'})>}
- _default_error_messages = {'type': 'Invalid input type.', 'unknown': 'Unknown field.'}
- _deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._T]]
Deserialize
data
.- Parameters
data (dict) – The data to deserialize.
error_store (ErrorStore) – Structure to store errors.
many (bool) – True if
data
should be deserialized as a collection.partial (bool|tuple) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE.
index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.
- Returns
A dictionary of the deserialized data.
- _do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)
Deserialize data, returning the deserialized result. This method is private API.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.
unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
postprocess – Whether to run post_load methods..
- Returns
Deserialized data
- _has_processors(tag) bool
- _hooks = {('pre_load', False): ['process_input']}
- _init_fields() None
Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.
- _invoke_dump_processors(tag: str, data, *, many: bool, original_data=None)
- _invoke_field_validators(*, error_store: marshmallow.error_store.ErrorStore, data, many: bool)
- _invoke_load_processors(tag: str, data, *, many: bool, original_data, partial: Union[bool, Sequence[str], Set[str]])
- _invoke_processors(tag: str, *, pass_many: bool, data, many: bool, original_data=None, **kwargs)
- _invoke_schema_validators(*, error_store: marshmallow.error_store.ErrorStore, pass_many: bool, data, original_data, many: bool, partial: Union[bool, Sequence[str], Set[str]], field_errors: bool = False)
- _normalize_nested_options() None
Apply then flatten nested schema options. This method is private API.
- _run_validator(validator_func, output, *, original_data, error_store, many, partial, pass_original, index=None)
- _serialize(obj: Union[marshmallow.schema._T, Iterable[marshmallow.schema._T]], *, many: bool = False)
Serialize
obj
.- Parameters
obj – The object(s) to serialize.
many (bool) – True if
data
should be serialized as a collection.
- Returns
A dictionary of the serialized data
Changed in version 1.0.0: Renamed from
marshal
.
- property dict_class: type
- dump(obj: Any, *, many: Optional[bool] = None)
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
Serialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages = {}
Overrides for default schema-level error messages
- fields
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.Field, type]], *, name: str = 'GeneratedSchema') type
Generate a Schema class given a dictionary of fields.
from marshmallow import Schema, fields PersonSchema = Schema.from_dict({"name": fields.Str()}) print(PersonSchema().load({"name": "David"})) # => {'name': 'David'}
Generated schemas are not added to the class registry and therefore cannot be referred to by name in Nested fields.
- Parameters
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
repr
for the class.
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)
Defines how to pull values from an object to serialize.
New in version 2.0.0.
Changed in version 3.0.0a1: Changed position of
obj
andattr
.
- handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- jsonify(obj, many=<object object>, *args, **kwargs)
Return a JSON response containing the serialized data.
- Parameters
obj – Object to serialize.
many (bool) – Whether obj should be serialized as an instance or as a collection. If unset, defaults to the value of the many attribute on this Schema.
kwargs – Additional keyword arguments passed to flask.jsonify.
Changed in version 0.6.0: Takes the same arguments as marshmallow.Schema.dump. Additional keyword arguments are passed to flask.jsonify.
Changed in version 0.6.3: The many argument for this method defaults to the value of the many attribute on the Schema. Previously, the many argument of this method defaulted to False, regardless of the value of Schema.many.
- load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
- Returns
Deserialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)
duple. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)
Same as
load()
, except it takes a JSON string as input.- Parameters
json_data – A JSON string of the data to deserialize.
many – Whether to deserialize obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
- Returns
Deserialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)
duple. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: marshmallow.fields.Field) None
Hook to modify a field when it is bound to the Schema.
No-op by default.
- opts = <marshmallow.schema.SchemaOpts object>
- process_input(value, many, **kwargs)
- property set_class: type
- validate(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None) Dict[str, List[str]]
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.
- Returns
A dictionary of validation errors.
New in version 1.1.0.
- class app.serializers.user.UserSerializer(*, only: Optional[Union[Sequence[str], Set[str]]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)
-
- OPTIONS_CLASS
alias of
marshmallow.schema.SchemaOpts
- TYPE_MAPPING = {<class 'str'>: <class 'marshmallow.fields.String'>, <class 'bytes'>: <class 'marshmallow.fields.String'>, <class 'datetime.datetime'>: <class 'marshmallow.fields.DateTime'>, <class 'float'>: <class 'marshmallow.fields.Float'>, <class 'bool'>: <class 'marshmallow.fields.Boolean'>, <class 'tuple'>: <class 'marshmallow.fields.Raw'>, <class 'list'>: <class 'marshmallow.fields.Raw'>, <class 'set'>: <class 'marshmallow.fields.Raw'>, <class 'int'>: <class 'marshmallow.fields.Integer'>, <class 'uuid.UUID'>: <class 'marshmallow.fields.UUID'>, <class 'datetime.time'>: <class 'marshmallow.fields.Time'>, <class 'datetime.date'>: <class 'marshmallow.fields.Date'>, <class 'datetime.timedelta'>: <class 'marshmallow.fields.TimeDelta'>, <class 'decimal.Decimal'>: <class 'marshmallow.fields.Decimal'>}
- _bind_field(field_name: str, field_obj: marshmallow.fields.Field) None
Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was specified in
class Meta
.
- static _call_and_store(getter_func, data, *, field_name, error_store, index=None)
Call
getter_func
withdata
as its argument, and store any ValidationErrors.- Parameters
getter_func (callable) – Function for getting the serialized/deserialized value from
data
.data – The data passed to
getter_func
.field_name (str) – Field name.
index (int) – Index of the item being validated, if validating a collection, otherwise None.
- _declared_fields = {'active': <fields.Boolean(dump_default=<marshmallow.missing>, attribute=None, validate=None, required=False, load_only=False, dump_only=False, load_default=<marshmallow.missing>, allow_none=False, error_messages={'required': 'Missing data for required field.', 'null': 'Field may not be null.', 'validator_failed': 'Invalid value.', 'invalid': 'Not a valid boolean.'})>, 'birth_date': <fields.Date(dump_default=<marshmallow.missing>, attribute=None, validate=None, required=False, load_only=False, dump_only=False, load_default=<marshmallow.missing>, allow_none=False, error_messages={'required': 'Missing data for required field.', 'null': 'Field may not be null.', 'validator_failed': 'Invalid value.', 'invalid': 'Not a valid date.', 'invalid_awareness': 'Not a valid {awareness} {obj_type}.', 'format': '"{input}" cannot be formatted as a date.'})>, 'created_at': <fields.TimestampField(dump_default=<marshmallow.missing>, attribute=None, validate=None, required=False, load_only=False, dump_only=True, load_default=<marshmallow.missing>, allow_none=False, error_messages={'required': 'Missing data for required field.', 'null': 'Field may not be null.', 'validator_failed': 'Invalid value.'})>, 'created_by': <fields.Nested(dump_default=<marshmallow.missing>, attribute=None, validate=None, required=False, load_only=False, dump_only=False, load_default=<marshmallow.missing>, allow_none=False, error_messages={'required': 'Missing data for required field.', 'null': 'Field may not be null.', 'validator_failed': 'Invalid value.', 'type': 'Invalid type.'})>, 'deleted_at': <fields.TimestampField(dump_default=<marshmallow.missing>, attribute=None, validate=None, required=False, load_only=False, dump_only=True, load_default=<marshmallow.missing>, allow_none=False, error_messages={'required': 'Missing data for required field.', 'null': 'Field may not be null.', 'validator_failed': 'Invalid value.'})>, 'email': <fields.Email(dump_default=<marshmallow.missing>, attribute=None, validate=None, required=True, load_only=False, dump_only=False, load_default=<marshmallow.missing>, allow_none=False, error_messages={'required': 'Missing data for required field.', 'null': 'Field may not be null.', 'validator_failed': 'Invalid value.', 'invalid': 'Not a valid email address.', 'invalid_utf8': 'Not a valid utf-8 string.'})>, 'genre': <fields.String(dump_default=<marshmallow.missing>, attribute=None, validate=<OneOf(choices=['m', 'f'], labels=[], error='Must be one of: {choices}.')>, required=False, load_only=False, dump_only=False, load_default=<marshmallow.missing>, allow_none=False, error_messages={'required': 'Missing data for required field.', 'null': 'Field may not be null.', 'validator_failed': 'Invalid value.', 'invalid': 'Not a valid string.', 'invalid_utf8': 'Not a valid utf-8 string.'})>, 'id': <fields.Integer(dump_default=<marshmallow.missing>, attribute=None, validate=None, required=False, load_only=False, dump_only=False, load_default=<marshmallow.missing>, allow_none=False, error_messages={'required': 'Missing data for required field.', 'null': 'Field may not be null.', 'validator_failed': 'Invalid value.', 'invalid': 'Not a valid integer.', 'too_large': 'Number too large.'})>, 'last_name': <fields.String(dump_default=<marshmallow.missing>, attribute=None, validate=None, required=False, load_only=False, dump_only=False, load_default=<marshmallow.missing>, allow_none=False, error_messages={'required': 'Missing data for required field.', 'null': 'Field may not be null.', 'validator_failed': 'Invalid value.', 'invalid': 'Not a valid string.', 'invalid_utf8': 'Not a valid utf-8 string.'})>, 'name': <fields.String(dump_default=<marshmallow.missing>, attribute=None, validate=None, required=False, load_only=False, dump_only=False, load_default=<marshmallow.missing>, allow_none=False, error_messages={'required': 'Missing data for required field.', 'null': 'Field may not be null.', 'validator_failed': 'Invalid value.', 'invalid': 'Not a valid string.', 'invalid_utf8': 'Not a valid utf-8 string.'})>, 'password': <fields.String(dump_default=<marshmallow.missing>, attribute=None, validate=<Length(min=8, max=50, equal=None, error=None)>, required=False, load_only=True, dump_only=False, load_default=<marshmallow.missing>, allow_none=False, error_messages={'required': 'Missing data for required field.', 'null': 'Field may not be null.', 'validator_failed': 'Invalid value.', 'invalid': 'Not a valid string.', 'invalid_utf8': 'Not a valid utf-8 string.'})>, 'role_id': <fields.VerifyRoleId(dump_default=<marshmallow.missing>, attribute=None, validate=None, required=False, load_only=True, dump_only=False, load_default=<marshmallow.missing>, allow_none=False, error_messages={'required': 'Missing data for required field.', 'null': 'Field may not be null.', 'validator_failed': 'Invalid value.'})>, 'roles': <fields.List(dump_default=<marshmallow.missing>, attribute=None, validate=None, required=False, load_only=False, dump_only=True, load_default=<marshmallow.missing>, allow_none=False, error_messages={'required': 'Missing data for required field.', 'null': 'Field may not be null.', 'validator_failed': 'Invalid value.', 'invalid': 'Not a valid list.'})>, 'updated_at': <fields.TimestampField(dump_default=<marshmallow.missing>, attribute=None, validate=None, required=False, load_only=False, dump_only=True, load_default=<marshmallow.missing>, allow_none=False, error_messages={'required': 'Missing data for required field.', 'null': 'Field may not be null.', 'validator_failed': 'Invalid value.'})>}
- _default_error_messages = {'type': 'Invalid input type.', 'unknown': 'Unknown field.'}
- _deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._T]]
Deserialize
data
.- Parameters
data (dict) – The data to deserialize.
error_store (ErrorStore) – Structure to store errors.
many (bool) – True if
data
should be deserialized as a collection.partial (bool|tuple) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE.
index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.
- Returns
A dictionary of the deserialized data.
- _do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)
Deserialize data, returning the deserialized result. This method is private API.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.
unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
postprocess – Whether to run post_load methods..
- Returns
Deserialized data
- _has_processors(tag) bool
- _hooks = {'validates': ['validate_email', 'validate_id']}
- _init_fields() None
Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.
- _invoke_dump_processors(tag: str, data, *, many: bool, original_data=None)
- _invoke_field_validators(*, error_store: marshmallow.error_store.ErrorStore, data, many: bool)
- _invoke_load_processors(tag: str, data, *, many: bool, original_data, partial: Union[bool, Sequence[str], Set[str]])
- _invoke_processors(tag: str, *, pass_many: bool, data, many: bool, original_data=None, **kwargs)
- _invoke_schema_validators(*, error_store: marshmallow.error_store.ErrorStore, pass_many: bool, data, original_data, many: bool, partial: Union[bool, Sequence[str], Set[str]], field_errors: bool = False)
- _normalize_nested_options() None
Apply then flatten nested schema options. This method is private API.
- _run_validator(validator_func, output, *, original_data, error_store, many, partial, pass_original, index=None)
- _serialize(obj: Union[marshmallow.schema._T, Iterable[marshmallow.schema._T]], *, many: bool = False)
Serialize
obj
.- Parameters
obj – The object(s) to serialize.
many (bool) – True if
data
should be serialized as a collection.
- Returns
A dictionary of the serialized data
Changed in version 1.0.0: Renamed from
marshal
.
- property dict_class: type
- dump(obj: Any, *, many: Optional[bool] = None)
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
Serialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages = {}
Overrides for default schema-level error messages
- fields
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.Field, type]], *, name: str = 'GeneratedSchema') type
Generate a Schema class given a dictionary of fields.
from marshmallow import Schema, fields PersonSchema = Schema.from_dict({"name": fields.Str()}) print(PersonSchema().load({"name": "David"})) # => {'name': 'David'}
Generated schemas are not added to the class registry and therefore cannot be referred to by name in Nested fields.
- Parameters
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
repr
for the class.
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)
Defines how to pull values from an object to serialize.
New in version 2.0.0.
Changed in version 3.0.0a1: Changed position of
obj
andattr
.
- handle_error(error: marshmallow.exceptions.ValidationError, data: Any, *, many: bool, **kwargs)
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- jsonify(obj, many=<object object>, *args, **kwargs)
Return a JSON response containing the serialized data.
- Parameters
obj – Object to serialize.
many (bool) – Whether obj should be serialized as an instance or as a collection. If unset, defaults to the value of the many attribute on this Schema.
kwargs – Additional keyword arguments passed to flask.jsonify.
Changed in version 0.6.0: Takes the same arguments as marshmallow.Schema.dump. Additional keyword arguments are passed to flask.jsonify.
Changed in version 0.6.3: The many argument for this method defaults to the value of the many attribute on the Schema. Previously, the many argument of this method defaulted to False, regardless of the value of Schema.many.
- load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
- Returns
Deserialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)
duple. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)
Same as
load()
, except it takes a JSON string as input.- Parameters
json_data – A JSON string of the data to deserialize.
many – Whether to deserialize obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
- Returns
Deserialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)
duple. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: marshmallow.fields.Field) None
Hook to modify a field when it is bound to the Schema.
No-op by default.
- opts = <marshmallow.schema.SchemaOpts object>
- property set_class: type
- validate(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None) Dict[str, List[str]]
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.
- Returns
A dictionary of validation errors.
New in version 1.1.0.
- validate_email(email: str)
- validate_id(user_id: int)
- class app.serializers.user.VerifyRoleId(*, load_default: Any = <marshmallow.missing>, missing: Any = <marshmallow.missing>, dump_default: Any = <marshmallow.missing>, default: Any = <marshmallow.missing>, data_key: Optional[str] = None, attribute: Optional[str] = None, validate: Optional[Union[Callable[[Any], Any], Iterable[Callable[[Any], Any]]]] = None, required: bool = False, allow_none: Optional[bool] = None, load_only: bool = False, dump_only: bool = False, error_messages: Optional[Dict[str, str]] = None, metadata: Optional[Mapping[str, Any]] = None, **additional_metadata)
- _CHECK_ATTRIBUTE = True
- _bind_to_schema(field_name, schema)
Update field with values from its parent schema. Called by
Schema._bind_field
.- Parameters
field_name (str) – Field name set in schema.
schema (Schema|Field) – Parent object.
- _creation_index = 129
- _deserialize(value, *args, **kwargs)
Deserialize value. Concrete
Field
classes should implement this method.- Parameters
value – The value to be deserialized.
attr – The attribute/key in data to be deserialized.
data – The raw input data passed to the Schema.load.
kwargs – Field-specific keyword arguments.
- Raises
ValidationError – In case of formatting or validation failure.
- Returns
The deserialized value.
Changed in version 2.0.0: Added
attr
anddata
parameters.Changed in version 3.0.0: Added
**kwargs
to signature.
- _serialize(value: Any, attr: str, obj: Any, **kwargs)
Serializes
value
to a basic Python datatype. Noop by default. ConcreteField
classes should implement this method.Example:
class TitleCase(Field): def _serialize(self, value, attr, obj, **kwargs): if not value: return '' return str(value).title()
- Parameters
value – The value to be serialized.
attr (str) – The attribute or key on the object to be serialized.
obj (object) – The object the value was pulled from.
kwargs (dict) – Field-specific keyword arguments.
- Returns
The serialized value
- _validate(value)
Perform validation on
value
. Raise aValidationError
if validation does not succeed.
- property _validate_all
- _validate_missing(value)
Validate missing values. Raise a
ValidationError
if value should be considered missing.
- property context
The context dictionary for the parent
Schema
.
- property default
- default_error_messages = {'null': 'Field may not be null.', 'required': 'Missing data for required field.', 'validator_failed': 'Invalid value.'}
Default error messages for various kinds of errors. The keys in this dictionary are passed to Field.make_error. The values are error messages passed to
marshmallow.exceptions.ValidationError
.
- deserialize(value: Any, attr: Optional[str] = None, data: Optional[Mapping[str, Any]] = None, **kwargs)
Deserialize
value
.- Parameters
value – The value to deserialize.
attr – The attribute/key in data to deserialize.
data – The raw input data passed to Schema.load.
kwargs – Field-specific keyword arguments.
- Raises
ValidationError – If an invalid value is passed or if a required value is missing.
- fail(key: str, **kwargs)
Helper method that raises a ValidationError with an error message from
self.error_messages
.Deprecated since version 3.0.0: Use make_error <marshmallow.fields.Field.make_error> instead.
- get_value(obj, attr, accessor=None, default=<marshmallow.missing>)
Return the value for a given key from an object.
- Parameters
obj (object) – The object to get the value from.
attr (str) – The attribute/key in obj to get the value from.
accessor (callable) – A callable used to retrieve the value of attr from the object obj. Defaults to marshmallow.utils.get_value.
- make_error(key: str, **kwargs) marshmallow.exceptions.ValidationError
Helper method to make a ValidationError with an error message from
self.error_messages
.
- property missing
- name = None
- parent = None
- root = None
- serialize(attr: str, obj: Any, accessor: Optional[Callable[[Any, str, Any], Any]] = None, **kwargs)
Pulls the value for the given key from the object, applies the field’s formatting and returns the result.
- Parameters
attr – The attribute/key to get from the object.
obj – The object to access the attribute/key from.
accessor – Function used to access values from
obj
.kwargs – Field-specific keyword arguments.