mirror of
https://github.com/msgpack/msgpack-python.git
synced 2025-10-25 22:54:11 +00:00
Merge pull request #30 from drednout/docs_datetime
README improvement: example of usage default/object_hook
This commit is contained in:
commit
cf82b91c1a
1 changed files with 31 additions and 0 deletions
31
README.rst
31
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
|
||||
---------
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue