Changeset View
Changeset View
Standalone View
Standalone View
swh/model/model.py
Show All 26 Lines | |||||
SHA1_SIZE = 20 | SHA1_SIZE = 20 | ||||
# TODO: Limit this to 20 bytes | # TODO: Limit this to 20 bytes | ||||
Sha1Git = bytes | Sha1Git = bytes | ||||
class BaseModel: | |||||
"""Base class for SWH model classes. | |||||
Provides serialization/deserialization to/from Python dictionaries, | |||||
that are suitable for JSON/msgpack-like formats.""" | |||||
def to_dict(self): | |||||
"""Wrapper of `attr.asdict` that can be overridden by subclasses | |||||
that have special handling of some of the fields.""" | |||||
def dictify(value): | def dictify(value): | ||||
"Helper function used by BaseModel.to_dict()" | |||||
if isinstance(value, BaseModel): | if isinstance(value, BaseModel): | ||||
return value.to_dict() | return value.to_dict() | ||||
elif isinstance(value, Enum): | elif isinstance(value, Enum): | ||||
return value.value | return value.value | ||||
elif isinstance(value, dict): | elif isinstance(value, dict): | ||||
return {k: dictify(v) for k, v in value.items()} | return {k: dictify(v) for k, v in value.items()} | ||||
elif isinstance(value, list): | elif isinstance(value, list): | ||||
return [dictify(v) for v in value] | return [dictify(v) for v in value] | ||||
else: | else: | ||||
return value | return value | ||||
ret = attr.asdict(self, recurse=False) | |||||
return dictify(ret) | class BaseModel: | ||||
"""Base class for SWH model classes. | |||||
Provides serialization/deserialization to/from Python dictionaries, | |||||
that are suitable for JSON/msgpack-like formats.""" | |||||
def to_dict(self): | |||||
"""Wrapper of `attr.asdict` that can be overridden by subclasses | |||||
that have special handling of some of the fields.""" | |||||
return dictify(attr.asdict(self, recurse=False)) | |||||
@classmethod | @classmethod | ||||
def from_dict(cls, d): | def from_dict(cls, d): | ||||
"""Takes a dictionary representing a tree of SWH objects, and | """Takes a dictionary representing a tree of SWH objects, and | ||||
recursively builds the corresponding objects.""" | recursively builds the corresponding objects.""" | ||||
return cls(**d) | return cls(**d) | ||||
▲ Show 20 Lines • Show All 521 Lines • Show Last 20 Lines |