METADATA 8.3 KB

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