File: using_context.rst

package info (click to toggle)
python-marshmallow 3.26.1-0.4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,296 kB
  • sloc: python: 11,513; makefile: 11; sh: 8
file content (20 lines) | stat: -rw-r--r-- 847 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Using context
=============

.. warning::

    The ``context`` attribute is deprecated and will be removed in marshmallow 4.
    Use `contextvars.ContextVar` for passing context to fields, pre-/post-processing methods, and validators instead.
    marshmallow 4 will also provide an `experimental helper API <https://marshmallow.readthedocs.io/en/latest/marshmallow.experimental.context.html>`_
    for using context.

The ``context`` attribute of a `Schema <marshmallow.Schema>` is a general-purpose store for extra information that may be needed for (de)serialization. 
It may be used in both ``Schema`` and ``Field`` methods.

.. code-block:: python

    schema = UserSchema()
    # Make current HTTP request available to
    # custom fields, schema methods, schema validators, etc.
    schema.context["request"] = request
    schema.dump(user)