marshmallow多路复用模式
项目描述
marshmallow 的扩展,以支持模式(解)复用。
marshmallow 是一个用于数据序列化和反序列化的出色库。有关该项目更多信息,请参阅其 GitHub 页面或其 文档。
该库添加了一种特殊的模式,它根据对象类型来多路复用其他模式。在序列化值时,它使用get_obj_type()方法获取对象类型名称。然后它使用type_schemas名称到Schema的映射来获取特定对象类型的模式,使用该模式序列化对象并添加一个包含对象类型名称的额外字段。反序列化是相反的过程。
安装
$ pip install marshmallow-oneofschema
示例
以下代码演示了如何设置多态模式。完整上下文请查看测试。一旦设置好模式,它应该像任何其他模式一样工作。如果不这样,请提交一个问题。
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)]
默认情况下,get_obj_type()返回obj.__class__.__name__,所以您可以直接重用它以节省一些输入
class MyUberSchema(OneOfSchema):
type_schemas = {"Foo": FooSchema, "Bar": BarSchema}
您可以使用type_field类属性自定义类型字段
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}]
您可以在marshmallow.Schema可以使用的任何地方使用生成的模式,例如
import marshmallow as m
import marshmallow.fields as f
class MyOtherSchema(m.Schema):
items = f.List(f.Nested(MyUberSchema))
许可证
MIT许可。有关更多详细信息,请参阅捆绑的LICENSE文件。
项目详情
关闭
哈希值 for marshmallow_oneofschema-3.1.1-py3-none-any.whl
算法 | 哈希摘要 | |
---|---|---|
SHA256 | ff4cb2a488785ee8edd521a765682c2c80c78b9dc48894124531bdfa1ec9303b |
|
MD5 | 9c72a0c13dd0ee2cff01d6181b58cac7 |
|
BLAKE2b-256 | 5c813ef15337c19d3e3432945aad738081a5f54c16885277c7dff300b5f85b24 |