-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpolicy_serializer.py
44 lines (39 loc) · 1.51 KB
/
policy_serializer.py
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
39
40
41
42
43
44
import dataclasses
from datetime import datetime
import msgpack
from src.model.raw_csv import RawCsvGoodsOption, RawCsvPolicy
class PolicySerializer:
@classmethod
def serialize(cls, raw_map: dict[int, list[dataclasses.dataclass]]) -> bytes:
converted = {
k: [
dataclasses.asdict(opt) | {
'transaction_time': opt.transaction_time.isoformat(),
'started_at': opt.started_at.isoformat(),
'ended_at': opt.ended_at.isoformat(),
}
for opt in v
]
for k, v in raw_map.items()
}
return msgpack.packb(converted)
@classmethod
def deserialize(cls, data: bytes) -> dict[int, list[dataclasses.dataclass]]:
# Either use strict_map_key=False
data = msgpack.unpackb(data, strict_map_key=False)
# OR keep the keys as strings and convert back to int when processing
result = {}
for key, options in data.items():
# Convert string key back to int
result[int(key)] = [
RawCsvPolicy(
**{
**opt,
'transaction_time': datetime.fromisoformat(opt['transaction_time']),
'started_at': datetime.fromisoformat(opt['started_at']),
'ended_at': datetime.fromisoformat(opt['ended_at']),
}
)
for opt in options
]
return result