diff options
| author | Alexei Romanoff <drednout.by@gmail.com> | 2012-10-12 13:32:29 +0300 |
|---|---|---|
| committer | Alexei Romanoff <drednout.by@gmail.com> | 2012-10-12 13:32:29 +0300 |
| commit | 541d22d00434863ce1e3607950c199edbd2b850a (patch) | |
| tree | 2281e7bac0d1d7ea394bcb2df73608363c4d4895 /README.rst | |
| parent | cf89f18be7614d6d55bb9eb7e9bf0e10d42a8508 (diff) | |
| download | msgpack-python-541d22d00434863ce1e3607950c199edbd2b850a.tar.gz | |
Added example of using default/object_hook into README
Diffstat (limited to 'README.rst')
| -rw-r--r-- | README.rst | 30 |
1 files changed, 30 insertions, 0 deletions
@@ -61,6 +61,36 @@ 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 --------- |
