API Docs

Fields

Marshmallow fields.

class marshmallow_utils.fields.BabelGettextDictField(locale, default_locale, **kwargs)[source]

Translation string field (dump only).

This field dumps a translation string as output, by looking up the translation in the dictionary provided as input (the message catalog).

The lookup is performed via babel’s locale negotiation (e.g. en_US will also match en).

Basically the fields takes a data object like this:

{'title': {'en': 'Text', 'da': 'Tekst'}}

and dumps this (in case the locale is english):

{'title': 'Text'}

Initialize the field.

Parameters
  • locale – The locale to lookup, or a function returning the locale.

  • default_locale – The default locale in case the locale is not found. Can be a callable that returns the default locale.

default_error_messages = {'invalid': 'Not a valid dictionary.', 'missing_locale': 'Translation not found for '}

Default error messages.

property default_locale

Get the default locale to be used.

property locale

Get the locale to be used.

class marshmallow_utils.fields.EDTFDateString(**kwargs)[source]

Extended Date(/Time) Format Level 0 date string field.

A string field which an using the EDTF Validator.

Constructor.

class marshmallow_utils.fields.FormatDate(format='medium', locale='en_US_POSIX', parse=True, **kwargs)[source]

Format a date object.

Constructor.

Parameters
  • format – The format to use (either short, medium, long or full).

  • locale – The current locale or a callable returning the current locale.

format_value(value)[source]

Format an EDTF date.

class marshmallow_utils.fields.FormatDatetime(tzinfo=None, **kwargs)[source]

Format a datetime object.

Constructor.

format_value(value)[source]

Format an EDTF date.

property tzinfo

Get the timzone to use.

class marshmallow_utils.fields.FormatEDTF(format='medium', locale='en_US_POSIX', parse=True, **kwargs)[source]

Format an EDTF-formatted string.

Constructor.

Parameters
  • format – The format to use (either short, medium, long or full).

  • locale – The current locale or a callable returning the current locale.

format_value(value)[source]

Format an EDTF date.

class marshmallow_utils.fields.FormatTime(tzinfo=None, **kwargs)[source]

Format a time object.

Constructor.

format_value(value)[source]

Format an EDTF date.

class marshmallow_utils.fields.Function(serialize: None | Callable[[Any], Any] | Callable[[Any, dict], Any] = None, deserialize: None | Callable[[Any], Any] | Callable[[Any, dict], Any] = None, **kwargs)[source]

Enhanced marshmallow Function field.

The main difference between the original marshmallow.fields.Function is for the deserialize function, which can now also point to a three-argument function, with the third argument being the original data that was passed to Schema.load. The following example better demonstrates how this works:

def serialize_foo(obj, context):
    return {'serialize_args': {'obj': obj, 'context': context}}

def deserialize_foo(value, context, data):
    return {'deserialize_args': {
        'value': value, 'context': context, 'data': data}}

class FooSchema(marshmallow.Schema):

    foo = Function(serialize_foo, deserialize_foo)

FooSchema().dump({'foo': 42})
{'foo': {
    'serialize_args': {
        'obj': {'foo': 42},
        'context': {}  # no context was passed
    }
}}

FooSchema().load({'foo': 42}).data
{'foo': {
    'deserialize_args': {
        'value': 42,
        'context': {},  # no context was passed
        'data': {'foo': 42},
    }
}}
class marshmallow_utils.fields.GenFunction(serialize: None | Callable[[Any], Any] | Callable[[Any, dict], Any] = None, deserialize: None | Callable[[Any], Any] | Callable[[Any, dict], Any] = None, **kwargs)[source]

Function field which is always deserialized.

class marshmallow_utils.fields.GenMethod(serialize: str | None = None, deserialize: str | None = None, **kwargs)[source]

Method field which is always deserialized.

class marshmallow_utils.fields.ISODateString(format: str | None = None, **kwargs)[source]

ISO8601-formatted date string.

ISODateString serializes to a date string and if it can’t, the field is ignored (missing).

NOTE: It serializes None to None.

class marshmallow_utils.fields.ISOLangString(validate=<function validate_iso639_3>, *args, **kwargs)[source]

ISO language string field.

ISO language string field initialization.

class marshmallow_utils.fields.IdentifierSet(cls_or_instance: Field | type, **kwargs)[source]

Identifier list with deduplication.

It assumes the items of the list contain a scheme property.

default_error_messages = {'multiple_values': 'Only one identifier per scheme is allowed.'}

Default error messages.

A link field that knows how to generate a link from an object.

Constructor.

A links field that knows to look in the context for the schema.

class marshmallow_utils.fields.Method(serialize: str | None = None, deserialize: str | None = None, **kwargs)[source]

Enhanced marshmallow Method field.

The main difference between the original marshmallow.fields.Method is for the deserialize method, which can now also point to a two-argument method, with the second argument being the original data that was passed to Schema.load. The following example better demonstrates how this works:

class BarSchema(marshmallow.Schema):

    bar = Method('serialize_bar', 'deserialize_bar')

    # Exactly the same behavior as in ``marshmallow.fields.Method``
    def serialize_bar(self, obj):
        return {'serialize_args': {'obj': obj}}

    def deserialize_bar(self, value, data):
        return {'deserialize_args': {'value': value, 'data': data}}

BarSchema().dump({'bar': 42})
{'bar': {
    'serialize_args': {
        'obj': {'bar': 42}
    }
}}

BarSchema().load({'bar': 42})
{'bar': {
    'deserialize_args': {
        'data': {'bar': 42},
        'value': 42
    }
}}
class marshmallow_utils.fields.NestedAttribute(nested: SchemaABC | type | str | dict[str, Field | type] | typing.Callable[[], SchemaABC | dict[str, Field | type]], *, dump_default: typing.Any = <marshmallow.missing>, default: typing.Any = <marshmallow.missing>, only: types.StrSequenceOrSet | None = None, exclude: types.StrSequenceOrSet = (), many: bool = False, unknown: str | None = None, **kwargs)[source]

Nested object attribute field.

class marshmallow_utils.fields.SanitizedHTML(tags=None, attrs=None, *args, **kwargs)[source]

String field which sanitizes HTML using the bleach library.

The default list of allowed tags and attributes is defined by ALLOWED_HTML_TAGS and ALLOWED_HTML_ATTRS.

You can override the defaults like this:

class MySchema(Schema):
    html = fields.SanitizedHTML(tags=['a'], attrs={'a': ['href']})
Parameters
  • tags – List of allowed tags.

  • attrs – Dictionary of allowed attributes per tag.

Initialize field.

class marshmallow_utils.fields.SanitizedUnicode(*, load_default: typing.Any = <marshmallow.missing>, missing: typing.Any = <marshmallow.missing>, dump_default: typing.Any = <marshmallow.missing>, default: typing.Any = <marshmallow.missing>, data_key: str | None = None, attribute: str | None = None, validate: None | (typing.Callable[[typing.Any], typing.Any] | typing.Iterable[typing.Callable[[typing.Any], typing.Any]]) = None, required: bool = False, allow_none: bool | None = None, load_only: bool = False, dump_only: bool = False, error_messages: dict[str, str] | None = None, metadata: typing.Mapping[str, typing.Any] | None = None, **additional_metadata)[source]

String field that sanitizes and fixes problematic unicode characters.

class marshmallow_utils.fields.StrippedHTML(*, load_default: typing.Any = <marshmallow.missing>, missing: typing.Any = <marshmallow.missing>, dump_default: typing.Any = <marshmallow.missing>, default: typing.Any = <marshmallow.missing>, data_key: str | None = None, attribute: str | None = None, validate: None | (typing.Callable[[typing.Any], typing.Any] | typing.Iterable[typing.Callable[[typing.Any], typing.Any]]) = None, required: bool = False, allow_none: bool | None = None, load_only: bool = False, dump_only: bool = False, error_messages: dict[str, str] | None = None, metadata: typing.Mapping[str, typing.Any] | None = None, **additional_metadata)[source]

String field which strips HTML entities.

The value is stripped using the bleach library. Any already escaped value is being unescaped before return.

class marshmallow_utils.fields.TZDateTime(timezone=datetime.timezone.utc, format='iso', **kwargs)[source]

Datetime field which converts naive datetimes to TZ aware datetimes.

Defaults to setting the timezone to UTC, and using ISO format.

Initialize the field.

class marshmallow_utils.fields.TrimmedString(*, load_default: typing.Any = <marshmallow.missing>, missing: typing.Any = <marshmallow.missing>, dump_default: typing.Any = <marshmallow.missing>, default: typing.Any = <marshmallow.missing>, data_key: str | None = None, attribute: str | None = None, validate: None | (typing.Callable[[typing.Any], typing.Any] | typing.Iterable[typing.Callable[[typing.Any], typing.Any]]) = None, required: bool = False, allow_none: bool | None = None, load_only: bool = False, dump_only: bool = False, error_messages: dict[str, str] | None = None, metadata: typing.Mapping[str, typing.Any] | None = None, **additional_metadata)[source]

String field which strips whitespace at the ends of the string.

Schemas

Marshmallow schemas.

class marshmallow_utils.schemas.GeometryObjectSchema(*, only: types.StrSequenceOrSet | None = None, exclude: types.StrSequenceOrSet = (), many: bool = False, context: dict | None = None, load_only: types.StrSequenceOrSet = (), dump_only: types.StrSequenceOrSet = (), partial: bool | types.StrSequenceOrSet = False, unknown: str | None = None)[source]

A GeoJSON Geometry Object schema.

See https://tools.ietf.org/html/rfc7946#section-3.1

Only Point, MultiPoint and Polygon are supported.

get_obj_type(obj)[source]

Finds the object type in the dictionary.

This function is needed because the schemas return the dict itself. Not a geojson object.

class marshmallow_utils.schemas.IdentifierSchema(allowed_schemes, identifier_required=True, **kwargs)[source]

Identifier with automatic scheme detection.

Constructor.

Parameters
  • allowed_schemes – a dictionary of allowed schemes. Each key must contain a validator function and a scheme label.

  • identifier_required – True when the identifier value is required.

error_messages: Dict[str, str] = {'invalid_identifier': 'Invalid {scheme} identifier.', 'invalid_scheme': 'Invalid scheme.', 'required': 'Missing data for required field.', 'unknown_scheme': 'No valid scheme recognized for identifier.'}

Overrides for default schema-level error messages

load_scheme(data, **kwargs)[source]

Loads the scheme of the identifier.

normalize_identifier(data, **kwargs)[source]

Normalizes the identifier based on the scheme.

validate_identifier(data, **kwargs)[source]

Validate the identifier format and scheme.

class marshmallow_utils.schemas.MultiPointSchema(*, only: types.StrSequenceOrSet | None = None, exclude: types.StrSequenceOrSet = (), many: bool = False, context: dict | None = None, load_only: types.StrSequenceOrSet = (), dump_only: types.StrSequenceOrSet = (), partial: bool | types.StrSequenceOrSet = False, unknown: str | None = None)[source]

GeoJSON MultiPoint schema.

See https://tools.ietf.org/html/rfc7946#section-3.1.3

class marshmallow_utils.schemas.PointSchema(*, only: types.StrSequenceOrSet | None = None, exclude: types.StrSequenceOrSet = (), many: bool = False, context: dict | None = None, load_only: types.StrSequenceOrSet = (), dump_only: types.StrSequenceOrSet = (), partial: bool | types.StrSequenceOrSet = False, unknown: str | None = None)[source]

GeoJSON Point schema.

See https://tools.ietf.org/html/rfc7946#section-3.1.2

class marshmallow_utils.schemas.PolygonSchema(*, only: types.StrSequenceOrSet | None = None, exclude: types.StrSequenceOrSet = (), many: bool = False, context: dict | None = None, load_only: types.StrSequenceOrSet = (), dump_only: types.StrSequenceOrSet = (), partial: bool | types.StrSequenceOrSet = False, unknown: str | None = None)[source]

GeoJSON Polygon schema.

See https://tools.ietf.org/html/rfc7946#section-3.1.6