-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmodel.py
More file actions
38 lines (27 loc) · 837 Bytes
/
model.py
File metadata and controls
38 lines (27 loc) · 837 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import json
class SpecialDefault:
pass
class Model:
id: str
def __init__(self, **kwargs):
data = {}
for field in self.__dataclass_fields__.values():
data[field.name] = kwargs.get(field.name, field.default)
for key, value in data.items():
if isinstance(value, SpecialDefault):
value = value.get(data)
setattr(self, key, value)
def to_dict(self):
data = {'id': self.id}
for field in self.__dataclass_fields__:
data[field] = getattr(self, field)
return data
def to_json(self):
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, data):
data = json.loads(data)
id = data.pop('id', None)
obj = cls(**data)
obj.id = id
return obj