File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -61,6 +61,36 @@ stream.
6161 for unpacked in unpacker:
6262 print unpacked
6363
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+
6494
6595INSTALL
6696---------
You can’t perform that action at this time.
0 commit comments