Skip to main content

Marshmallow multiplexing schema

Project description

Build Status

An extenstion 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 page or its Documentation.

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

Importing

Here is how to import the necessary field class

from marshmallow_oneofschema import OneOfSchema

Example

The code below demonstrates how to setup a schema with a PolyField. 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.

import marshmallow
import marshmallow.fields
from marshmallow_oneofschema import OneOfSchema

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

class Bar(object):
    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):
        return Foo(**data)

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

    @marshmallow.post_load
    def make_bar(self, data):
        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: %s' % obj.__class__.__name__)

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

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

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

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

You can customize type field with type_field class property:

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

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

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

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 file for more details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

marshmallow-oneofschema-1.0.3.tar.gz (4.8 kB view details)

Uploaded Source

Built Distribution

marshmallow_oneofschema-1.0.3-py2.py3-none-any.whl (8.2 kB view details)

Uploaded Python 2 Python 3

File details

Details for the file marshmallow-oneofschema-1.0.3.tar.gz.

File metadata

File hashes

Hashes for marshmallow-oneofschema-1.0.3.tar.gz
Algorithm Hash digest
SHA256 62df51f0497edcf3954bcb630cda7cae6a294517ab575aa56cdd618058334c96
MD5 3211aabaa0ad6ad99aefcc37a94475ed
BLAKE2b-256 61b9e07b6006cea93b0f023f645fac9decfffea8b56becaed8c0dc2348966a5f

See more details on using hashes here.

File details

Details for the file marshmallow_oneofschema-1.0.3-py2.py3-none-any.whl.

File metadata

File hashes

Hashes for marshmallow_oneofschema-1.0.3-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 d8dd37b5802610e4790409c10bcd8d6fb5de8733bed4144980078e4478afb5b9
MD5 3e30b7460afb072c7356aacc13186a39
BLAKE2b-256 68957a1002f21810fd8c880a02668f6e2e12f2eed0be7e09dbbf59351e12435b

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page