Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python DDD中实体序列化的处理_Python_Serialization_Entity_Domain Driven Design - Fatal编程技术网

Python DDD中实体序列化的处理

Python DDD中实体序列化的处理,python,serialization,entity,domain-driven-design,Python,Serialization,Entity,Domain Driven Design,我有一个场景,其中一个实体定义了一个从另一端创建的实体表示。EntityRepresentation是一个值对象,它实现了传输后应在另一端执行的一些逻辑。最后,EntityRepresentation和实体包含相同的数据,但在第一种情况下,它存储为Python基类型(在我的情况下为字符串),事实上,EntityMapper对象用于在两种类型之间进行映射,以便存储从EntityRepresentation映射的实体 换句话说,EntityRepresentation包含与实体相同的数据,但采用由实

我有一个场景,其中一个
实体
定义了一个从另一端创建的
实体表示
EntityRepresentation
是一个值对象,它实现了传输后应在另一端执行的一些逻辑。最后,
EntityRepresentation
实体
包含相同的数据,但在第一种情况下,它存储为Python基类型(在我的情况下为字符串),事实上,
EntityMapper
对象用于在两种类型之间进行映射,以便存储从
EntityRepresentation
映射的
实体

换句话说,
EntityRepresentation
包含与
实体
相同的数据,但采用由
实体
确定的可序列化格式。因为我试图坚持DDD,所以我知道我所做的是否被认为是反模式的。我对这个设计有点怀疑,因为我觉得我可以只使用
实体
类,并且表示格式可以通过在两端使用一个方法来处理。事实上,此表示不应与
实体
道具一起存储,因为它将来可能会更改

既然我的域对其施加了约束,那么让
实体
提供一种方法来创建其自身的可序列化表示将有多正确

下面是一个示例代码:

import json


class Entity:

    def __init__(self, id: str, name: str, type: str):
        self.id = id
        self.name = name
        self.type = type


class EntityRepresentation:

    def __init__(self, data: str = None):
        if data is None:
            d = {
                "id": "ID",
                "name": "NAME",
                "type": "TYPE"
            }
            self.data = json.dumps(d)
        else:
            self.data = data

    def process(self):
        # performs ops on self.data
        return True


class EntityMapper:

    def fromRepr(self, repr: EntityRepresentation) -> Entity:
        return json.loads(repr.data, object_hook=lambda r: Entity(**r))

    def toRepr(self, ent: Entity) -> EntityRepresentation:
        return EntityRepresentation(json.dumps(ent.__dict__))


def main():

    mapper = EntityMapper()

    # the representation is created on the first end
    e_repr = EntityRepresentation()

    # serialization
    e_repr_json = json.dumps(e_repr.data)

    # the json is sent into a wire
    # it is then received and deserialized on the other end
    e_repr_rec: EntityRepresentation = json.loads(
        json.loads(e_repr_json), object_hook=lambda d: EntityRepresentation(json.dumps(d)))

    if e_repr_rec.process():
        print(mapper.fromRepr(e_repr_rec))

    return 0


if __name__ == '__main__':
    main()