8000 Added example of using default/object_hook into README · twigtek/msgpack-python@541d22d · GitHub
[go: up one dir, main page]

Skip to content

Commit 541d22d

Browse files
committed
Added example of using default/object_hook into README
1 parent cf89f18 commit 541d22d

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

README.rst

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff 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

6595
INSTALL
6696
---------

0 commit comments

Comments
 (0)
0