对棉花糖的非正式扩展,以允许多态字段

marshmallow-polyfield的Python项目详细描述


Documentation StatusBuild StatusCoverage Status

此分支支持棉花糖3.0及以上版本。有关2.0支持,请参见The 2.0 branch

棉花糖的一个非正式扩展,允许多晶领域。

marshmallow是一个很棒的数据序列化和反序列化库。 有关该项目的更多信息,请参见其GitHub页或Documentation

此项目添加了一个为多态类型设计的自定义字段。这允许您定义一个模式,该模式表示“此字段接受x类型的任何内容”

这个领域的秘密是你需要定义两个函数。一个用于序列化,另一个用于反序列化。这些功能 接受原始值并返回要使用的架构。

该字段应支持与其他棉花糖字段相同的属性。我和requiredallow_nonemany一起工作过。

上一版本支持v2标记为final v2版本

安装

$ pip install marshmallow-polyfield

导入

下面是如何导入必需的字段类

from marshmallow_polyfield import PolyField

示例

下面的代码演示如何使用polyfield设置模式。有关完整上下文,请查看测试。 一旦设置好架构,它就应该像其他任何架构一样工作。如果没有,请提出一个问题。

defshape_schema_serialization_disambiguation(base_object,parent_obj):class_to_schema={Rectangle.__name__:RectangleSchema,Triangle.__name__:TriangleSchema}try:returnclass_to_schema[base_object.__class__.__name__]()exceptKeyError:passraiseTypeError("Could not detect type. ""Did not have a base or a length. ""Are you sure this is a shape?")defshape_schema_deserialization_disambiguation(object_dict,parent_object_dict):ifobject_dict.get("base"):returnTriangleSchema()elifobject_dict.get("length"):returnRectangleSchema()raiseTypeError("Could not detect type. ""Did not have a base or a length. ""Are you sure this is a shape?")classContrivedShapeClass(object):def__init__(self,main,others):self.main=mainself.others=othersdef__eq__(self,other):returnself.__dict__==other.__dict__classContrivedShapeClassSchema(Schema):main=PolyField(serialization_schema_selector=shape_schema_serialization_disambiguation,deserialization_schema_selector=shape_schema_deserialization_disambiguation,required=True)others=PolyField(serialization_schema_selector=shape_schema_serialization_disambiguation,deserialization_schema_selector=shape_schema_deserialization_disambiguation,allow_none=True,many=True)@post_loaddefmake_object(self,data):returnTestPolyField.ContrivedShapeClass(data.get('main'),data.get('others'))

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java Grid loadmask(true)在gxt中不起作用   java将字符串索引转换为整数   为什么Java泛型适用于基元数组,但不适用于基元数组?   java如何让Azure应用程序服务Tomcat将所有80/443流量转发到运行在同一应用程序服务上的JBoss   具有多个值的java转换映射到树?   java如何设置SQL server连接URL?   java设置了多个相互独立的JFrame   安全性在JAVA中如何使用RSAPrivateKey的密码短语?   java不能使用比Apache Velocity中更大的条件   如何在Java中打印字符串的所有排列   停止Android Studio自动导入java。sql。日期   对象简单计算器程序java   java如何在安卓中使用“&”符号作为字符串?   java Connect,为我的安卓应用程序从REST API发布和获取数据