DESCRIPTION.rst 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. =======================
  2. MessagePack for Python
  3. =======================
  4. :author: INADA Naoki
  5. :version: 0.4.6
  6. :date: 2015-03-13
  7. .. image:: https://secure.travis-ci.org/msgpack/msgpack-python.png
  8. :target: https://travis-ci.org/#!/msgpack/msgpack-python
  9. What's this
  10. ------------
  11. `MessagePack <http://msgpack.org/>`_ is a fast, compact binary serialization format, suitable for
  12. similar data to JSON. This package provides CPython bindings for reading and
  13. writing MessagePack data.
  14. Install
  15. ---------
  16. ::
  17. $ pip install msgpack-python
  18. PyPy
  19. ^^^^^
  20. msgpack-python provides pure python implementation. PyPy can use this.
  21. Windows
  22. ^^^^^^^
  23. When you can't use binary distribution, you need to install Visual Studio
  24. or Windows SDK on Windows.
  25. Without extension, using pure python implementation on CPython runs slowly.
  26. For Python 2.7, `Microsoft Visual C++ Compiler for Python 2.7 <https://www.microsoft.com/en-us/download/details.aspx?id=44266>`_
  27. is recommended solution.
  28. For Python 3.5, `Microsoft Visual Studio 2015 <https://www.visualstudio.com/en-us/products/vs-2015-product-editions.aspx>`_
  29. Community Edition or Express Edition can be used to build extension module.
  30. How to use
  31. -----------
  32. One-shot pack & unpack
  33. ^^^^^^^^^^^^^^^^^^^^^^
  34. Use ``packb`` for packing and ``unpackb`` for unpacking.
  35. msgpack provides ``dumps`` and ``loads`` as alias for compatibility with
  36. ``json`` and ``pickle``.
  37. ``pack`` and ``dump`` packs to file-like object.
  38. ``unpack`` and ``load`` unpacks from file-like object.
  39. .. code-block:: pycon
  40. >>> import msgpack
  41. >>> msgpack.packb([1, 2, 3])
  42. '\x93\x01\x02\x03'
  43. >>> msgpack.unpackb(_)
  44. [1, 2, 3]
  45. ``unpack`` unpacks msgpack's array to Python's list, but can unpack to tuple:
  46. .. code-block:: pycon
  47. >>> msgpack.unpackb(b'\x93\x01\x02\x03', use_list=False)
  48. (1, 2, 3)
  49. You should always pass the ``use_list`` keyword argument. See performance issues relating to `use_list option`_ below.
  50. Read the docstring for other options.
  51. Streaming unpacking
  52. ^^^^^^^^^^^^^^^^^^^
  53. ``Unpacker`` is a "streaming unpacker". It unpacks multiple objects from one
  54. stream (or from bytes provided through its ``feed`` method).
  55. .. code-block:: python
  56. import msgpack
  57. from io import BytesIO
  58. buf = BytesIO()
  59. for i in range(100):
  60. buf.write(msgpack.packb(range(i)))
  61. buf.seek(0)
  62. unpacker = msgpack.Unpacker(buf)
  63. for unpacked in unpacker:
  64. print unpacked
  65. Packing/unpacking of custom data type
  66. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  67. It is also possible to pack/unpack custom data types. Here is an example for
  68. ``datetime.datetime``.
  69. .. code-block:: python
  70. import datetime
  71. import msgpack
  72. useful_dict = {
  73. "id": 1,
  74. "created": datetime.datetime.now(),
  75. }
  76. def decode_datetime(obj):
  77. if b'__datetime__' in obj:
  78. obj = datetime.datetime.strptime(obj["as_str"], "%Y%m%dT%H:%M:%S.%f")
  79. return obj
  80. def encode_datetime(obj):
  81. if isinstance(obj, datetime.datetime):
  82. return {'__datetime__': True, 'as_str': obj.strftime("%Y%m%dT%H:%M:%S.%f")}
  83. return obj
  84. packed_dict = msgpack.packb(useful_dict, default=encode_datetime)
  85. this_dict_again = msgpack.unpackb(packed_dict, object_hook=decode_datetime)
  86. ``Unpacker``'s ``object_hook`` callback receives a dict; the
  87. ``object_pairs_hook`` callback may instead be used to receive a list of
  88. key-value pairs.
  89. Extended types
  90. ^^^^^^^^^^^^^^^
  91. It is also possible to pack/unpack custom data types using the **ext** type.
  92. .. code-block:: pycon
  93. >>> import msgpack
  94. >>> import array
  95. >>> def default(obj):
  96. ... if isinstance(obj, array.array) and obj.typecode == 'd':
  97. ... return msgpack.ExtType(42, obj.tostring())
  98. ... raise TypeError("Unknown type: %r" % (obj,))
  99. ...
  100. >>> def ext_hook(code, data):
  101. ... if code == 42:
  102. ... a = array.array('d')
  103. ... a.fromstring(data)
  104. ... return a
  105. ... return ExtType(code, data)
  106. ...
  107. >>> data = array.array('d', [1.2, 3.4])
  108. >>> packed = msgpack.packb(data, default=default)
  109. >>> unpacked = msgpack.unpackb(packed, ext_hook=ext_hook)
  110. >>> data == unpacked
  111. True
  112. Advanced unpacking control
  113. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  114. As an alternative to iteration, ``Unpacker`` objects provide ``unpack``,
  115. ``skip``, ``read_array_header`` and ``read_map_header`` methods. The former two
  116. read an entire message from the stream, respectively deserialising and returning
  117. the result, or ignoring it. The latter two methods return the number of elements
  118. in the upcoming container, so that each element in an array, or key-value pair
  119. in a map, can be unpacked or skipped individually.
  120. Each of these methods may optionally write the packed data it reads to a
  121. callback function:
  122. .. code-block:: python
  123. from io import BytesIO
  124. def distribute(unpacker, get_worker):
  125. nelems = unpacker.read_map_header()
  126. for i in range(nelems):
  127. # Select a worker for the given key
  128. key = unpacker.unpack()
  129. worker = get_worker(key)
  130. # Send the value as a packed message to worker
  131. bytestream = BytesIO()
  132. unpacker.skip(bytestream.write)
  133. worker.send(bytestream.getvalue())
  134. Notes
  135. -----
  136. string and binary type
  137. ^^^^^^^^^^^^^^^^^^^^^^
  138. In old days, msgpack doesn't distinguish string and binary types like Python 1.
  139. The type for represent string and binary types is named **raw**.
  140. msgpack can distinguish string and binary type for now. But it is not like Python 2.
  141. Python 2 added unicode string. But msgpack renamed **raw** to **str** and added **bin** type.
  142. It is because keep compatibility with data created by old libs. **raw** was used for text more than binary.
  143. Currently, while msgpack-python supports new **bin** type, default setting doesn't use it and
  144. decodes **raw** as `bytes` instead of `unicode` (`str` in Python 3).
  145. You can change this by using `use_bin_type=True` option in Packer and `encoding="utf-8"` option in Unpacker.
  146. .. code-block:: pycon
  147. >>> import msgpack
  148. >>> packed = msgpack.packb([b'spam', u'egg'], use_bin_type=True)
  149. >>> msgpack.unpackb(packed, encoding='utf-8')
  150. ['spam', u'egg']
  151. ext type
  152. ^^^^^^^^
  153. To use **ext** type, pass ``msgpack.ExtType`` object to packer.
  154. .. code-block:: pycon
  155. >>> import msgpack
  156. >>> packed = msgpack.packb(msgpack.ExtType(42, b'xyzzy'))
  157. >>> msgpack.unpackb(packed)
  158. ExtType(code=42, data='xyzzy')
  159. You can use it with ``default`` and ``ext_hook``. See below.
  160. Note for msgpack-python 0.2.x users
  161. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  162. The msgpack-python 0.3 have some incompatible changes.
  163. The default value of ``use_list`` keyword argument is ``True`` from 0.3.
  164. You should pass the argument explicitly for backward compatibility.
  165. `Unpacker.unpack()` and some unpack methods now raises `OutOfData`
  166. instead of `StopIteration`.
  167. `StopIteration` is used for iterator protocol only.
  168. Note about performance
  169. ------------------------
  170. GC
  171. ^^
  172. CPython's GC starts when growing allocated object.
  173. This means unpacking may cause useless GC.
  174. You can use ``gc.disable()`` when unpacking large message.
  175. use_list option
  176. ^^^^^^^^^^^^^^^^
  177. List is the default sequence type of Python.
  178. But tuple is lighter than list.
  179. You can use ``use_list=False`` while unpacking when performance is important.
  180. Python's dict can't use list as key and MessagePack allows array for key of mapping.
  181. ``use_list=False`` allows unpacking such message.
  182. Another way to unpacking such object is using ``object_pairs_hook``.
  183. Development
  184. ------------
  185. Test
  186. ^^^^
  187. MessagePack uses `pytest` for testing.
  188. Run test with following command:
  189. $ py.test
  190. ..
  191. vim: filetype=rst