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

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如何启用TLSv1。3在Tomcat8.5.5中使用JSSE实现   java表单post在jsp中,contentType头没有字符集,为什么?   java My Basic货币转换器程序输出错误   java在Eclipse4中单击最后一个部件(选项卡)时动态创建部件   java 2 servlet,一个在响应中获得ContentLength,另一个则没有   JavaStruts2:如何发送url参数?   linux从java运行bash文件   java TransactionRequiredException执行更新/删除查询   java如何使用JTA插入到表中?   从枚举到泛型的类型的java映射   java使用接口类<T>作为键来获取具体的实例值?