File tree 1 file changed +30
-0
lines changed 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change @@ -61,6 +61,36 @@ stream.
61
61
for unpacked in unpacker:
62
62
print unpacked
63
63
64
+ packing/unpacking of custom data type
65
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
66
+
67
+ Also possible to pack/unpack user's data types. Here is an example for
68
+ ``datetime.datetime ``.
69
+
70
+ ::
71
+ import datetime
72
+
73
+ import msgpack
74
+
75
+ useful_dict = {
76
+ "id": 1,
77
+ "created": datetime.datetime.now(),
78
+ }
79
+
80
+ def decode_datetime(obj):
81
+ if b'__datetime__' in obj:
82
+ obj = datetime.datetime.strptime(obj["as_str"], "%Y%m%dT%H:%M:%S.%f")
83
+ return obj
84
+
85
+ def encode_datetime(obj):
86
+ if isinstance(obj, datetime.datetime):
87
+ return {'__datetime__': True, 'as_str': obj.strftime("%Y%m%dT%H:%M:%S.%f")}
88
+ return obj
89
+
90
+
91
+ packed_dict = msgpack.packb(useful_dict, default=encode_datetime)
92
+ this_dict_again = msgpack.unpackb(packed_dict, object_hook=decode_datetime)
93
+
64
94
65
95
INSTALL
66
96
---------
You can’t perform that action at this time.
0 commit comments