summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorINADA Naoki <songofacandy@gmail.com>2012-10-12 05:49:32 -0700
committerINADA Naoki <songofacandy@gmail.com>2012-10-12 05:49:32 -0700
commitcf82b91c1a9b78d571882331c89b943b8d84f1cf (patch)
treedafcb9b0ead85886d71339d9ef4ed5905f6ce2e9
parent8f822526870c3775d9c8a38514c2c6c3d2ce4e5f (diff)
parentfa1c4745ec4c8cf8bad5f35be8ddb7fd9e28532e (diff)
downloadmsgpack-python-cf82b91c1a9b78d571882331c89b943b8d84f1cf.tar.gz
Merge pull request #30 from drednout/docs_datetime
README improvement: example of usage default/object_hook
-rw-r--r--README.rst31
1 files changed, 31 insertions, 0 deletions
diff --git a/README.rst b/README.rst
index 1da6ece..834c86c 100644
--- a/README.rst
+++ b/README.rst
@@ -61,6 +61,37 @@ stream.
for unpacked in unpacker:
print unpacked
+packing/unpacking of custom data type
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Also possible to pack/unpack user's data types. Here is an example for
+``datetime.datetime``.
+
+::
+
+ import datetime
+
+ import msgpack
+
+ useful_dict = {
+ "id": 1,
+ "created": datetime.datetime.now(),
+ }
+
+ def decode_datetime(obj):
+ if b'__datetime__' in obj:
+ obj = datetime.datetime.strptime(obj["as_str"], "%Y%m%dT%H:%M:%S.%f")
+ return obj
+
+ def encode_datetime(obj):
+ if isinstance(obj, datetime.datetime):
+ return {'__datetime__': True, 'as_str': obj.strftime("%Y%m%dT%H:%M:%S.%f")}
+ return obj
+
+
+ packed_dict = msgpack.packb(useful_dict, default=encode_datetime)
+ this_dict_again = msgpack.unpackb(packed_dict, object_hook=decode_datetime)
+
INSTALL
---------