不可思议的快速对象序列化
serp的Python项目详细描述
serpy是为提高速度而构建的超级简单的对象序列化框架。 serpy将复杂数据类型(django模型、自定义类,…)序列化为 简单的本机类型(dict、list、string…)。本机类型很容易 转换为json或任何其他需要的格式。
serpy的目标是能够做到这一点simply,reliably,以及 快速。因为序列化程序是基于类的,所以它们可以组合、扩展 并且只需要很少的代码重复就可以定制。与其他流行的 python序列化框架如marshmallow或Django Rest Framework Serializersserpy位于 至少快一点。
安装
$ pip install serpy
示例
简单示例
importserpyclassFoo(object):"""The object to be serialized."""y='hello'z=9.5def__init__(self,x):self.x=xclassFooSerializer(serpy.Serializer):"""The serializer schema definition."""# Use a Field subclass like IntField if you need more validation.x=serpy.IntField()y=serpy.Field()z=serpy.Field()f=Foo(1)FooSerializer(f).data# {'x': 1, 'y': 'hello', 'z': 9.5}fs=[Foo(i)foriinrange(100)]FooSerializer(fs,many=True).data# [{'x': 0, 'y': 'hello', 'z': 9.5}, {'x': 1, 'y': 'hello', 'z': 9.5}, ...]
嵌套示例
importserpyclassNestee(object):"""An object nested inside another object."""n='hi'classFoo(object):x=1nested=Nestee()classNesteeSerializer(serpy.Serializer):n=serpy.Field()classFooSerializer(serpy.Serializer):x=serpy.Field()# Use another serializer as a field.nested=NesteeSerializer()f=Foo()FooSerializer(f).data# {'x': 1, 'nested': {'n': 'hi'}}
复杂示例
importserpyclassFoo(object):y=1z=2super_long_thing=10defx(self):return5classFooSerializer(serpy.Serializer):w=serpy.Field(attr='super_long_thing')x=serpy.Field(call=True)plus=serpy.MethodField()defget_plus(self,obj):returnobj.y+obj.zf=Foo()FooSerializer(f).data# {'w': 10, 'x': 5, 'plus': 3}
继承示例
importserpyclassFoo(object):a=1b=2classASerializer(serpy.Serializer):a=serpy.Field()classABSerializer(ASerializer):"""ABSerializer inherits the 'a' field from ASerializer. This also works with multiple inheritance and mixins. """b=serpy.Field()f=Foo()ASerializer(f).data# {'a': 1}ABSerializer(f).data# {'a': 1, 'b': 2}
许可证
serpy是根据mit许可条款发布的自由软件。见 LICENSE文件。