Skip to content

Commit 3707e2e

Browse files
committed
pref: pickle decoder support type datetime
1 parent f70121b commit 3707e2e

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

backend/utils/convert/pickle_convert.go

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,21 @@ import base64
1414
import json
1515
import pickle
1616
import sys
17+
from datetime import datetime
18+
19+
def default_serializer(o):
20+
if isinstance(o, datetime):
21+
return o.isoformat()
22+
return str(o)
23+
24+
def object_hook(obj):
25+
for k, v in obj.items():
26+
if isinstance(v, str):
27+
try:
28+
obj[k] = datetime.fromisoformat(v)
29+
except ValueError:
30+
pass
31+
return obj
1732
1833
if __name__ == "__main__":
1934
if len(sys.argv) >= 3:
@@ -24,11 +39,11 @@ if __name__ == "__main__":
2439
if action == 'decode':
2540
decoded = base64.b64decode(content)
2641
obj = pickle.loads(decoded)
27-
unserialized = json.dumps(obj, ensure_ascii=False)
42+
unserialized = json.dumps(obj, ensure_ascii=False, default=default_serializer)
2843
print(base64.b64encode(unserialized.encode('utf-8')).decode('utf-8'))
2944
elif action == 'encode':
3045
decoded = base64.b64decode(content)
31-
obj = json.loads(decoded)
46+
obj = json.loads(decoded, object_hook=object_hook)
3247
serialized = pickle.dumps(obj)
3348
print(base64.b64encode(serialized).decode('utf-8'))
3449
except:

0 commit comments

Comments
 (0)