marshmallow-oneofschema


Namemarshmallow-oneofschema JSON
Version 3.1.1 PyPI version JSON
download
home_page
Summarymarshmallow multiplexing schema
upload_time2024-02-13 17:49:13
maintainer
docs_urlNone
author
requires_python>=3.8
license
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            =======================
marshmallow-oneofschema
=======================

.. image:: https://github.com/marshmallow-code/marshmallow-oneofschema/actions/workflows/build-release.yml/badge.svg
    :target: https://github.com/marshmallow-code/flask-marshmallow/actions/workflows/build-release.yml
    :alt: Build Status

.. image:: https://badgen.net/badge/marshmallow/3
    :target: https://marshmallow.readthedocs.io/en/latest/upgrading.html
    :alt: marshmallow 3 compatible

An extension to marshmallow to support schema (de)multiplexing.

marshmallow is a fantastic library for serialization and deserialization of data.
For more on that project see its `GitHub <https://github.com/marshmallow-code/marshmallow>`_
page or its `Documentation <http://marshmallow.readthedocs.org/en/latest/>`_.

This library adds a special kind of schema that actually multiplexes other schemas
based on object type. When serializing values, it uses get_obj_type() method
to get object type name. Then it uses ``type_schemas`` name-to-Schema mapping
to get schema for that particular object type, serializes object using that
schema and adds an extra field with name of object type. Deserialization is reverse.

Installing
----------

::

    $ pip install marshmallow-oneofschema

Example
-------

The code below demonstrates how to set up a polymorphic schema. For the full context check out the tests.
Once setup the schema should act like any other schema. If it does not then please file an Issue.

.. code:: python

    import marshmallow
    import marshmallow.fields
    from marshmallow_oneofschema import OneOfSchema


    class Foo:
        def __init__(self, foo):
            self.foo = foo


    class Bar:
        def __init__(self, bar):
            self.bar = bar


    class FooSchema(marshmallow.Schema):
        foo = marshmallow.fields.String(required=True)

        @marshmallow.post_load
        def make_foo(self, data, **kwargs):
            return Foo(**data)


    class BarSchema(marshmallow.Schema):
        bar = marshmallow.fields.Integer(required=True)

        @marshmallow.post_load
        def make_bar(self, data, **kwargs):
            return Bar(**data)


    class MyUberSchema(OneOfSchema):
        type_schemas = {"foo": FooSchema, "bar": BarSchema}

        def get_obj_type(self, obj):
            if isinstance(obj, Foo):
                return "foo"
            elif isinstance(obj, Bar):
                return "bar"
            else:
                raise Exception("Unknown object type: {}".format(obj.__class__.__name__))


    MyUberSchema().dump([Foo(foo="hello"), Bar(bar=123)], many=True)
    # => [{'type': 'foo', 'foo': 'hello'}, {'type': 'bar', 'bar': 123}]

    MyUberSchema().load(
        [{"type": "foo", "foo": "hello"}, {"type": "bar", "bar": 123}], many=True
    )
    # => [Foo('hello'), Bar(123)]

By default get_obj_type() returns obj.__class__.__name__, so you can just reuse that
to save some typing:

.. code:: python

    class MyUberSchema(OneOfSchema):
        type_schemas = {"Foo": FooSchema, "Bar": BarSchema}

You can customize type field with `type_field` class property:

.. code:: python

    class MyUberSchema(OneOfSchema):
        type_field = "object_type"
        type_schemas = {"Foo": FooSchema, "Bar": BarSchema}


    MyUberSchema().dump([Foo(foo="hello"), Bar(bar=123)], many=True)
    # => [{'object_type': 'Foo', 'foo': 'hello'}, {'object_type': 'Bar', 'bar': 123}]

You can use resulting schema everywhere marshmallow.Schema can be used, e.g.

.. code:: python

    import marshmallow as m
    import marshmallow.fields as f


    class MyOtherSchema(m.Schema):
        items = f.List(f.Nested(MyUberSchema))

License
-------

MIT licensed. See the bundled `LICENSE <https://github.com/marshmallow-code/marshmallow-oneofschema/blob/master/LICENSE>`_ file for more details.


            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "marshmallow-oneofschema",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": "Steven Loria <sloria1@gmail.com>",
    "keywords": "",
    "author": "",
    "author_email": "Maxim Kulkin <maxim.kulkin@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/35/75/8dd134f08375845910d134e50246fdfcab3f1d84ab3284bd09bb15f69be9/marshmallow_oneofschema-3.1.1.tar.gz",
    "platform": null,
    "description": "=======================\nmarshmallow-oneofschema\n=======================\n\n.. image:: https://github.com/marshmallow-code/marshmallow-oneofschema/actions/workflows/build-release.yml/badge.svg\n    :target: https://github.com/marshmallow-code/flask-marshmallow/actions/workflows/build-release.yml\n    :alt: Build Status\n\n.. image:: https://badgen.net/badge/marshmallow/3\n    :target: https://marshmallow.readthedocs.io/en/latest/upgrading.html\n    :alt: marshmallow 3 compatible\n\nAn extension to marshmallow to support schema (de)multiplexing.\n\nmarshmallow is a fantastic library for serialization and deserialization of data.\nFor more on that project see its `GitHub <https://github.com/marshmallow-code/marshmallow>`_\npage or its `Documentation <http://marshmallow.readthedocs.org/en/latest/>`_.\n\nThis library adds a special kind of schema that actually multiplexes other schemas\nbased on object type. When serializing values, it uses get_obj_type() method\nto get object type name. Then it uses ``type_schemas`` name-to-Schema mapping\nto get schema for that particular object type, serializes object using that\nschema and adds an extra field with name of object type. Deserialization is reverse.\n\nInstalling\n----------\n\n::\n\n    $ pip install marshmallow-oneofschema\n\nExample\n-------\n\nThe code below demonstrates how to set up a polymorphic schema. For the full context check out the tests.\nOnce setup the schema should act like any other schema. If it does not then please file an Issue.\n\n.. code:: python\n\n    import marshmallow\n    import marshmallow.fields\n    from marshmallow_oneofschema import OneOfSchema\n\n\n    class Foo:\n        def __init__(self, foo):\n            self.foo = foo\n\n\n    class Bar:\n        def __init__(self, bar):\n            self.bar = bar\n\n\n    class FooSchema(marshmallow.Schema):\n        foo = marshmallow.fields.String(required=True)\n\n        @marshmallow.post_load\n        def make_foo(self, data, **kwargs):\n            return Foo(**data)\n\n\n    class BarSchema(marshmallow.Schema):\n        bar = marshmallow.fields.Integer(required=True)\n\n        @marshmallow.post_load\n        def make_bar(self, data, **kwargs):\n            return Bar(**data)\n\n\n    class MyUberSchema(OneOfSchema):\n        type_schemas = {\"foo\": FooSchema, \"bar\": BarSchema}\n\n        def get_obj_type(self, obj):\n            if isinstance(obj, Foo):\n                return \"foo\"\n            elif isinstance(obj, Bar):\n                return \"bar\"\n            else:\n                raise Exception(\"Unknown object type: {}\".format(obj.__class__.__name__))\n\n\n    MyUberSchema().dump([Foo(foo=\"hello\"), Bar(bar=123)], many=True)\n    # => [{'type': 'foo', 'foo': 'hello'}, {'type': 'bar', 'bar': 123}]\n\n    MyUberSchema().load(\n        [{\"type\": \"foo\", \"foo\": \"hello\"}, {\"type\": \"bar\", \"bar\": 123}], many=True\n    )\n    # => [Foo('hello'), Bar(123)]\n\nBy default get_obj_type() returns obj.__class__.__name__, so you can just reuse that\nto save some typing:\n\n.. code:: python\n\n    class MyUberSchema(OneOfSchema):\n        type_schemas = {\"Foo\": FooSchema, \"Bar\": BarSchema}\n\nYou can customize type field with `type_field` class property:\n\n.. code:: python\n\n    class MyUberSchema(OneOfSchema):\n        type_field = \"object_type\"\n        type_schemas = {\"Foo\": FooSchema, \"Bar\": BarSchema}\n\n\n    MyUberSchema().dump([Foo(foo=\"hello\"), Bar(bar=123)], many=True)\n    # => [{'object_type': 'Foo', 'foo': 'hello'}, {'object_type': 'Bar', 'bar': 123}]\n\nYou can use resulting schema everywhere marshmallow.Schema can be used, e.g.\n\n.. code:: python\n\n    import marshmallow as m\n    import marshmallow.fields as f\n\n\n    class MyOtherSchema(m.Schema):\n        items = f.List(f.Nested(MyUberSchema))\n\nLicense\n-------\n\nMIT licensed. See the bundled `LICENSE <https://github.com/marshmallow-code/marshmallow-oneofschema/blob/master/LICENSE>`_ file for more details.\n\n",
    "bugtrack_url": null,
    "license": "",
    "summary": "marshmallow multiplexing schema",
    "version": "3.1.1",
    "project_urls": {
        "Funding": "https://opencollective.com/marshmallow",
        "Issues": "https://github.com/marshmallow-code/marshmallow-oneofschema/issues",
        "Source": "https://github.com/marshmallow-code/marshmallow-oneofschema"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "5c813ef15337c19d3e3432945aad738081a5f54c16885277c7dff300b5f85b24",
                "md5": "9c72a0c13dd0ee2cff01d6181b58cac7",
                "sha256": "ff4cb2a488785ee8edd521a765682c2c80c78b9dc48894124531bdfa1ec9303b"
            },
            "downloads": -1,
            "filename": "marshmallow_oneofschema-3.1.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "9c72a0c13dd0ee2cff01d6181b58cac7",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 5726,
            "upload_time": "2024-02-13T17:49:07",
            "upload_time_iso_8601": "2024-02-13T17:49:07.059521Z",
            "url": "https://files.pythonhosted.org/packages/5c/81/3ef15337c19d3e3432945aad738081a5f54c16885277c7dff300b5f85b24/marshmallow_oneofschema-3.1.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "35758dd134f08375845910d134e50246fdfcab3f1d84ab3284bd09bb15f69be9",
                "md5": "2cb3dfcfc9619db6880265e477ad243c",
                "sha256": "68b4a57d0281a04ac25d4eb7a4c5865a57090a0a8fd30fd6362c8e833ac6a6d9"
            },
            "downloads": -1,
            "filename": "marshmallow_oneofschema-3.1.1.tar.gz",
            "has_sig": false,
            "md5_digest": "2cb3dfcfc9619db6880265e477ad243c",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 8684,
            "upload_time": "2024-02-13T17:49:13",
            "upload_time_iso_8601": "2024-02-13T17:49:13.718734Z",
            "url": "https://files.pythonhosted.org/packages/35/75/8dd134f08375845910d134e50246fdfcab3f1d84ab3284bd09bb15f69be9/marshmallow_oneofschema-3.1.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-02-13 17:49:13",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "marshmallow-code",
    "github_project": "marshmallow-oneofschema",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "tox": true,
    "lcname": "marshmallow-oneofschema"
}
        
Elapsed time: 0.27644s