OpenQuizz
Une application de gestion des contenus pédagogiques
Schema Class Reference
Inheritance diagram for Schema:
Collaboration diagram for Schema:

Data Structures

class  Meta
 

Public Member Functions

def __init__ (self, *typing.Optional[types.StrSequenceOrSet] only=None, types.StrSequenceOrSet exclude=(), bool many=False, typing.Optional[typing.Dict] context=None, types.StrSequenceOrSet load_only=(), types.StrSequenceOrSet dump_only=(), typing.Union[bool, types.StrSequenceOrSet] partial=False, typing.Optional[str] unknown=None)
 
str __repr__ (self)
 
type dict_class (self)
 
type set_class (self)
 
type from_dict (cls, typing.Dict[str, typing.Union[ma_fields.Field, type]] fields, *str name="GeneratedSchema")
 
def handle_error (self, ValidationError error, typing.Any data, *bool many, **kwargs)
 Override-able methods #####. More...
 
def get_attribute (self, typing.Any obj, str attr, typing.Any default)
 
def dump (self, typing.Any obj, *typing.Optional[bool] many=None)
 
def dumps (self, typing.Any obj, *args, typing.Optional[bool] many=None, **kwargs)
 
def load (self, typing.Union[typing.Mapping[str, typing.Any], typing.Iterable[typing.Mapping[str, typing.Any]],] data, *typing.Optional[bool] many=None, typing.Optional[typing.Union[bool, types.StrSequenceOrSet]] partial=None, typing.Optional[str] unknown=None)
 
def loads (self, str json_data, *typing.Optional[bool] many=None, typing.Optional[typing.Union[bool, types.StrSequenceOrSet]] partial=None, typing.Optional[str] unknown=None, **kwargs)
 
typing.Dict[str, typing.List[str]] validate (self, typing.Mapping data, *typing.Optional[bool] many=None, typing.Optional[typing.Union[bool, types.StrSequenceOrSet]] partial=None)
 
None on_bind_field (self, str field_name, ma_fields.Field field_obj)
 
- Public Member Functions inherited from SchemaABC
def dump (self, obj, *typing.Optional[bool] many=None)
 
def dumps (self, obj, *typing.Optional[bool] many=None)
 
def load (self, data, *typing.Optional[bool] many=None, partial=None, unknown=None)
 
def loads (self, json_data, *typing.Optional[bool] many=None, partial=None, unknown=None, **kwargs)
 
- Public Member Functions inherited from SchemaMeta
def __new__ (mcs, name, bases, attrs)
 
def get_declared_fields (mcs, type klass, typing.List cls_fields, typing.List inherited_fields, type dict_cls)
 
def __init__ (cls, name, bases, attrs)
 
typing.Dict[types.Tag, typing.List[str]] resolve_hooks (cls)
 

Data Fields

 declared_fields
 
 many
 
 only
 
 exclude
 
 ordered
 
 load_only
 
 dump_only
 
 partial
 
 unknown
 
 context
 
 fields
 
 load_fields
 
 dump_fields
 

Static Public Attributes

 TYPE_MAPPING
 
 error_messages
 
 OPTIONS_CLASS
 
 opts
 
 maxsize
 

Detailed Description

Base schema class with which to define custom schemas.

Example usage:

.. code-block:: python

    import datetime as dt
    from dataclasses import dataclass

    from marshmallow import Schema, fields


    @dataclass
    class Album:
        title: str
        release_date: dt.date


    class AlbumSchema(Schema):
        title = fields.Str()
        release_date = fields.Date()


    album = Album("Beggars Banquet", dt.date(1968, 12, 6))
    schema = AlbumSchema()
    data = schema.dump(album)
    data  # {'release_date': '1968-12-06', 'title': 'Beggars Banquet'}

:param only: Whitelist of the declared fields to select when
    instantiating the Schema. If None, all fields are used. Nested fields
    can be represented with dot delimiters.
:param exclude: Blacklist of the declared fields to exclude
    when instantiating the Schema. If a field appears in both `only` and
    `exclude`, it is not used. Nested fields can be represented with dot
    delimiters.
:param many: Should be set to `True` if ``obj`` is a collection
    so that the object will be serialized to a list.
:param context: Optional context passed to :class:`fields.Method` and
    :class:`fields.Function` fields.
:param load_only: Fields to skip during serialization (write-only fields)
:param dump_only: Fields to skip during deserialization (read-only fields)
:param 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.
:param unknown: Whether to exclude, include, or raise an error for unknown
    fields in the data. Use `EXCLUDE`, `INCLUDE` or `RAISE`.

.. versionchanged:: 3.0.0
    `prefix` parameter removed.

.. versionchanged:: 2.0.0
    `__validators__`, `__preprocessors__`, and `__data_handlers__` are removed in favor of
    `marshmallow.decorators.validates_schema`,
    `marshmallow.decorators.pre_load` and `marshmallow.decorators.post_dump`.
    `__accessor__` and `__error_handler__` are deprecated. Implement the
    `handle_error` and `get_attribute` methods instead.

Constructor & Destructor Documentation

◆ __init__()

def __init__ (   self,
*typing.Optional[types.StrSequenceOrSet]   only = None,
types.StrSequenceOrSet   exclude = (),
bool   many = False,
typing.Optional[typing.Dict]   context = None,
types.StrSequenceOrSet   load_only = (),
types.StrSequenceOrSet   dump_only = (),
typing.Union[bool, types.StrSequenceOrSet]   partial = False,
typing.Optional[str]   unknown = None 
)

Member Function Documentation

◆ __repr__()

str __repr__ (   self)

◆ dict_class()

type dict_class (   self)

◆ dump()

def dump (   self,
typing.Any  obj,
*typing.Optional[bool]   many = None 
)
Serialize an object to native Python data types according to this
Schema's fields.

:param obj: The object to serialize.
:param many: Whether to serialize `obj` as a collection. If `None`, the value
    for `self.many` is used.
:return: Serialized data

.. versionadded:: 1.0.0
.. versionchanged:: 3.0.0b7
    This method returns the serialized data rather than a ``(data, errors)`` duple.
    A :exc:`ValidationError <marshmallow.exceptions.ValidationError>` is raised
    if ``obj`` is invalid.
.. versionchanged:: 3.0.0rc9
    Validation no longer occurs upon serialization.

◆ dumps()

def dumps (   self,
typing.Any  obj,
args,
typing.Optional[bool]   many = None,
**  kwargs 
)
Same as :meth:`dump`, except return a JSON-encoded string.

:param obj: The object to serialize.
:param many: Whether to serialize `obj` as a collection. If `None`, the value
    for `self.many` is used.
:return: A ``json`` string

.. versionadded:: 1.0.0
.. versionchanged:: 3.0.0b7
    This method returns the serialized data rather than a ``(data, errors)`` duple.
    A :exc:`ValidationError <marshmallow.exceptions.ValidationError>` is raised
    if ``obj`` is invalid.

◆ from_dict()

type from_dict (   cls,
typing.Dict[str, typing.Union[ma_fields.Field, type]]  fields,
*str   name = "GeneratedSchema" 
)
Generate a `Schema` class given a dictionary of fields.

.. code-block:: python

    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.

:param dict fields: Dictionary mapping field names to field instances.
:param str name: Optional name for the class, which will appear in
    the ``repr`` for the class.

.. versionadded:: 3.0.0

◆ get_attribute()

def get_attribute (   self,
typing.Any  obj,
str  attr,
typing.Any  default 
)
Defines how to pull values from an object to serialize.

.. versionadded:: 2.0.0

.. versionchanged:: 3.0.0a1
    Changed position of ``obj`` and ``attr``.

◆ handle_error()

def handle_error (   self,
ValidationError  error,
typing.Any  data,
*bool  many,
**  kwargs 
)

Override-able methods #####.

Custom error handler function for the schema.

:param error: The `ValidationError` raised during (de)serialization.
:param data: The original input data.
:param many: Value of ``many`` on dump or load.
:param partial: Value of ``partial`` on load.

.. versionadded:: 2.0.0

.. versionchanged:: 3.0.0rc9
    Receives `many` and `partial` (on deserialization) as keyword arguments.

◆ load()

def load (   self,
typing.Union[ typing.Mapping[str, typing.Any], typing.Iterable[typing.Mapping[str, typing.Any]], ]  data,
*typing.Optional[bool]   many = None,
typing.Optional[typing.Union[bool, types.StrSequenceOrSet]]   partial = None,
typing.Optional[str]   unknown = None 
)
Deserialize a data structure to an object defined by this Schema's fields.

:param data: The data to deserialize.
:param many: Whether to deserialize `data` as a collection. If `None`, the
    value for `self.many` is used.
:param 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.
:param 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.
:return: Deserialized data

.. versionadded:: 1.0.0
.. versionchanged:: 3.0.0b7
    This method returns the deserialized data rather than a ``(data, errors)`` duple.
    A :exc:`ValidationError <marshmallow.exceptions.ValidationError>` is raised
    if invalid data are passed.

◆ loads()

def loads (   self,
str  json_data,
*typing.Optional[bool]   many = None,
typing.Optional[typing.Union[bool, types.StrSequenceOrSet]]   partial = None,
typing.Optional[str]   unknown = None,
**  kwargs 
)
Same as :meth:`load`, except it takes a JSON string as input.

:param json_data: A JSON string of the data to deserialize.
:param many: Whether to deserialize `obj` as a collection. If `None`, the
    value for `self.many` is used.
:param 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.
:param 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.
:return: Deserialized data

.. versionadded:: 1.0.0
.. versionchanged:: 3.0.0b7
    This method returns the deserialized data rather than a ``(data, errors)`` duple.
    A :exc:`ValidationError <marshmallow.exceptions.ValidationError>` is raised
    if invalid data are passed.

◆ on_bind_field()

None on_bind_field (   self,
str  field_name,
ma_fields.Field  field_obj 
)
Hook to modify a field when it is bound to the `Schema`.

No-op by default.

◆ set_class()

type set_class (   self)

◆ validate()

typing.Dict[str, typing.List[str]] validate (   self,
typing.Mapping  data,
*typing.Optional[bool]   many = None,
typing.Optional[typing.Union[bool, types.StrSequenceOrSet]]   partial = None 
)
Validate `data` against the schema, returning a dictionary of
validation errors.

:param data: The data to validate.
:param many: Whether to validate `data` as a collection. If `None`, the
    value for `self.many` is used.
:param 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.
:return: A dictionary of validation errors.

.. versionadded:: 1.1.0

Field Documentation

◆ context

context

◆ declared_fields

declared_fields

◆ dump_fields

dump_fields

◆ dump_only

dump_only

◆ error_messages

error_messages
static

◆ exclude

exclude

◆ fields

fields

◆ load_fields

load_fields

◆ load_only

load_only

◆ many

many

◆ maxsize

maxsize
static

◆ only

only

◆ OPTIONS_CLASS

OPTIONS_CLASS
static

◆ opts

opts
static

◆ ordered

ordered

◆ partial

partial

◆ TYPE_MAPPING

TYPE_MAPPING
static

◆ unknown

unknown

The documentation for this class was generated from the following file: