All Projects → marshmallow-code → Marshmallow Oneofschema

marshmallow-code / Marshmallow Oneofschema

Licence: mit
Marshmallow library extension that allows schema (de)multiplexing

Programming Languages

python
139335 projects - #7 most used programming language

Projects that are alternatives of or similar to Marshmallow Oneofschema

Apispec
A pluggable API specification generator. Currently supports the OpenAPI Specification (f.k.a. the Swagger specification)..
Stars: ✭ 831 (+784.04%)
Mutual labels:  marshmallow, hacktoberfest
Environs
simplified environment variable parsing
Stars: ✭ 631 (+571.28%)
Mutual labels:  marshmallow, hacktoberfest
Marshmallow Sqlalchemy
SQLAlchemy integration with marshmallow
Stars: ✭ 426 (+353.19%)
Mutual labels:  marshmallow, hacktoberfest
Webargs
A friendly library for parsing HTTP request arguments, with built-in support for popular web frameworks, including Flask, Django, Bottle, Tornado, Pyramid, webapp2, Falcon, and aiohttp.
Stars: ✭ 1,145 (+1118.09%)
Mutual labels:  marshmallow, hacktoberfest
Adyen Php Api Library
Adyen API Library for PHP
Stars: ✭ 93 (-1.06%)
Mutual labels:  hacktoberfest
Atox
Reasonable Tox client for Android
Stars: ✭ 90 (-4.26%)
Mutual labels:  hacktoberfest
Tutorialdb
A search 🔎 engine for programming/dev tutorials, See it in action 👉
Stars: ✭ 93 (-1.06%)
Mutual labels:  hacktoberfest
Prisma Docs Generator
Prisma generator for automatically generating documentation reference from the Prisma schema.
Stars: ✭ 91 (-3.19%)
Mutual labels:  hacktoberfest
Polybar Kdeconnect
KDEConnect module for Polybar
Stars: ✭ 94 (+0%)
Mutual labels:  hacktoberfest
Kotlinfixture
Fixtures for Kotlin providing generated values for unit testing
Stars: ✭ 94 (+0%)
Mutual labels:  hacktoberfest
Arduino Amiibo Tools
Arduino sketches to play with amiibo
Stars: ✭ 93 (-1.06%)
Mutual labels:  hacktoberfest
Bin
~/bin
Stars: ✭ 93 (-1.06%)
Mutual labels:  hacktoberfest
Plexdrive
Plexdrive mounts your Google Drive FUSE filesystem (optimized for media playback)
Stars: ✭ 1,324 (+1308.51%)
Mutual labels:  hacktoberfest
Tasklite
The CLI task manager for power users
Stars: ✭ 91 (-3.19%)
Mutual labels:  hacktoberfest
Hotel booking app
🏩 📑 ❤️ Demo application for hotel booking app made with @flutter and love.
Stars: ✭ 94 (+0%)
Mutual labels:  hacktoberfest
Pywizlight
A python connector for WiZ light bulbs (e.g SLV Play)
Stars: ✭ 92 (-2.13%)
Mutual labels:  hacktoberfest
Coteafs Appium
📱 Wrapper Appium Framework in Java which supports Automation of Mobile and Tablet apps.
Stars: ✭ 93 (-1.06%)
Mutual labels:  hacktoberfest
Laravel Make Scope
Brings make:scope command to laravel
Stars: ✭ 94 (+0%)
Mutual labels:  hacktoberfest
Deautherdroid
Additional android app for SpaceHunn's ESP8266 DeAuther.
Stars: ✭ 93 (-1.06%)
Mutual labels:  hacktoberfest
Play
The free and open source karaoke singing game UltraStar Play for Windows, Linux, Android, Xbox, PlayStation and other platforms.
Stars: ✭ 94 (+0%)
Mutual labels:  hacktoberfest

======================= marshmallow-oneofschema

.. image:: https://dev.azure.com/sloria/sloria/_apis/build/status/marshmallow-code.marshmallow-oneofschema?branchName=master :target: https://dev.azure.com/sloria/sloria/_build/latest?definitionId=13&branchName=master :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.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].