You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

338 lines
9.6 KiB

4 years ago
  1. ======================
  2. MessagePack for Python
  3. ======================
  4. .. image:: https://travis-ci.org/msgpack/msgpack-python.svg?branch=master
  5. :target: https://travis-ci.org/msgpack/msgpack-python
  6. :alt: Build Status
  7. .. image:: https://readthedocs.org/projects/msgpack-python/badge/?version=latest
  8. :target: https://msgpack-python.readthedocs.io/en/latest/?badge=latest
  9. :alt: Documentation Status
  10. What's this
  11. -----------
  12. `MessagePack <https://msgpack.org/>`_ is an efficient binary serialization format.
  13. It lets you exchange data among multiple languages like JSON.
  14. But it's faster and smaller.
  15. This package provides CPython bindings for reading and writing MessagePack data.
  16. Very important notes for existing users
  17. ---------------------------------------
  18. PyPI package name
  19. ^^^^^^^^^^^^^^^^^
  20. TL;DR: When upgrading from msgpack-0.4 or earlier, don't do `pip install -U msgpack-python`.
  21. Do `pip uninstall msgpack-python; pip install msgpack` instead.
  22. Package name on PyPI was changed to msgpack from 0.5.
  23. I upload transitional package (msgpack-python 0.5 which depending on msgpack)
  24. for smooth transition from msgpack-python to msgpack.
  25. Sadly, this doesn't work for upgrade install. After `pip install -U msgpack-python`,
  26. msgpack is removed and `import msgpack` fail.
  27. Deprecating encoding option
  28. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  29. encoding and unicode_errors options are deprecated.
  30. In case of packer, use UTF-8 always. Storing other than UTF-8 is not recommended.
  31. For backward compatibility, you can use ``use_bin_type=False`` and pack ``bytes``
  32. object into msgpack raw type.
  33. In case of unpacker, there is new ``raw`` option. It is ``True`` by default
  34. for backward compatibility, but it is changed to ``False`` in near future.
  35. You can use ``raw=False`` instead of ``encoding='utf-8'``.
  36. Planned backward incompatible changes
  37. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  38. When msgpack 1.0, I planning these breaking changes:
  39. * packer and unpacker: Remove ``encoding`` and ``unicode_errors`` option.
  40. * packer: Change default of ``use_bin_type`` option from False to True.
  41. * unpacker: Change default of ``raw`` option from True to False.
  42. * unpacker: Reduce all ``max_xxx_len`` options for typical usage.
  43. * unpacker: Remove ``write_bytes`` option from all methods.
  44. To avoid these breaking changes breaks your application, please:
  45. * Don't use deprecated options.
  46. * Pass ``use_bin_type`` and ``raw`` options explicitly.
  47. * If your application handle large (>1MB) data, specify ``max_xxx_len`` options too.
  48. Install
  49. -------
  50. ::
  51. $ pip install msgpack
  52. PyPy
  53. ^^^^
  54. msgpack provides a pure Python implementation. PyPy can use this.
  55. Windows
  56. ^^^^^^^
  57. When you can't use a binary distribution, you need to install Visual Studio
  58. or Windows SDK on Windows.
  59. Without extension, using pure Python implementation on CPython runs slowly.
  60. For Python 2.7, `Microsoft Visual C++ Compiler for Python 2.7 <https://www.microsoft.com/en-us/download/details.aspx?id=44266>`_
  61. is recommended solution.
  62. For Python 3.5, `Microsoft Visual Studio 2015 <https://www.visualstudio.com/en-us/products/vs-2015-product-editions.aspx>`_
  63. Community Edition or Express Edition can be used to build extension module.
  64. How to use
  65. ----------
  66. One-shot pack & unpack
  67. ^^^^^^^^^^^^^^^^^^^^^^
  68. Use ``packb`` for packing and ``unpackb`` for unpacking.
  69. msgpack provides ``dumps`` and ``loads`` as an alias for compatibility with
  70. ``json`` and ``pickle``.
  71. ``pack`` and ``dump`` packs to a file-like object.
  72. ``unpack`` and ``load`` unpacks from a file-like object.
  73. .. code-block:: pycon
  74. >>> import msgpack
  75. >>> msgpack.packb([1, 2, 3], use_bin_type=True)
  76. '\x93\x01\x02\x03'
  77. >>> msgpack.unpackb(_, raw=False)
  78. [1, 2, 3]
  79. ``unpack`` unpacks msgpack's array to Python's list, but can also unpack to tuple:
  80. .. code-block:: pycon
  81. >>> msgpack.unpackb(b'\x93\x01\x02\x03', use_list=False, raw=False)
  82. (1, 2, 3)
  83. You should always specify the ``use_list`` keyword argument for backward compatibility.
  84. See performance issues relating to `use_list option`_ below.
  85. Read the docstring for other options.
  86. Streaming unpacking
  87. ^^^^^^^^^^^^^^^^^^^
  88. ``Unpacker`` is a "streaming unpacker". It unpacks multiple objects from one
  89. stream (or from bytes provided through its ``feed`` method).
  90. .. code-block:: python
  91. import msgpack
  92. from io import BytesIO
  93. buf = BytesIO()
  94. for i in range(100):
  95. buf.write(msgpack.packb(range(i), use_bin_type=True))
  96. buf.seek(0)
  97. unpacker = msgpack.Unpacker(buf, raw=False)
  98. for unpacked in unpacker:
  99. print(unpacked)
  100. Packing/unpacking of custom data type
  101. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  102. It is also possible to pack/unpack custom data types. Here is an example for
  103. ``datetime.datetime``.
  104. .. code-block:: python
  105. import datetime
  106. import msgpack
  107. useful_dict = {
  108. "id": 1,
  109. "created": datetime.datetime.now(),
  110. }
  111. def decode_datetime(obj):
  112. if b'__datetime__' in obj:
  113. obj = datetime.datetime.strptime(obj["as_str"], "%Y%m%dT%H:%M:%S.%f")
  114. return obj
  115. def encode_datetime(obj):
  116. if isinstance(obj, datetime.datetime):
  117. return {'__datetime__': True, 'as_str': obj.strftime("%Y%m%dT%H:%M:%S.%f")}
  118. return obj
  119. packed_dict = msgpack.packb(useful_dict, default=encode_datetime, use_bin_type=True)
  120. this_dict_again = msgpack.unpackb(packed_dict, object_hook=decode_datetime, raw=False)
  121. ``Unpacker``'s ``object_hook`` callback receives a dict; the
  122. ``object_pairs_hook`` callback may instead be used to receive a list of
  123. key-value pairs.
  124. Extended types
  125. ^^^^^^^^^^^^^^
  126. It is also possible to pack/unpack custom data types using the **ext** type.
  127. .. code-block:: pycon
  128. >>> import msgpack
  129. >>> import array
  130. >>> def default(obj):
  131. ... if isinstance(obj, array.array) and obj.typecode == 'd':
  132. ... return msgpack.ExtType(42, obj.tostring())
  133. ... raise TypeError("Unknown type: %r" % (obj,))
  134. ...
  135. >>> def ext_hook(code, data):
  136. ... if code == 42:
  137. ... a = array.array('d')
  138. ... a.fromstring(data)
  139. ... return a
  140. ... return ExtType(code, data)
  141. ...
  142. >>> data = array.array('d', [1.2, 3.4])
  143. >>> packed = msgpack.packb(data, default=default, use_bin_type=True)
  144. >>> unpacked = msgpack.unpackb(packed, ext_hook=ext_hook, raw=False)
  145. >>> data == unpacked
  146. True
  147. Advanced unpacking control
  148. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  149. As an alternative to iteration, ``Unpacker`` objects provide ``unpack``,
  150. ``skip``, ``read_array_header`` and ``read_map_header`` methods. The former two
  151. read an entire message from the stream, respectively de-serialising and returning
  152. the result, or ignoring it. The latter two methods return the number of elements
  153. in the upcoming container, so that each element in an array, or key-value pair
  154. in a map, can be unpacked or skipped individually.
  155. Each of these methods may optionally write the packed data it reads to a
  156. callback function:
  157. .. code-block:: python
  158. from io import BytesIO
  159. def distribute(unpacker, get_worker):
  160. nelems = unpacker.read_map_header()
  161. for i in range(nelems):
  162. # Select a worker for the given key
  163. key = unpacker.unpack()
  164. worker = get_worker(key)
  165. # Send the value as a packed message to worker
  166. bytestream = BytesIO()
  167. unpacker.skip(bytestream.write)
  168. worker.send(bytestream.getvalue())
  169. Notes
  170. -----
  171. string and binary type
  172. ^^^^^^^^^^^^^^^^^^^^^^
  173. Early versions of msgpack didn't distinguish string and binary types (like Python 1).
  174. The type for representing both string and binary types was named **raw**.
  175. For backward compatibility reasons, msgpack-python will still default all
  176. strings to byte strings, unless you specify the ``use_bin_type=True`` option in
  177. the packer. If you do so, it will use a non-standard type called **bin** to
  178. serialize byte arrays, and **raw** becomes to mean **str**. If you want to
  179. distinguish **bin** and **raw** in the unpacker, specify ``raw=False``.
  180. Note that Python 2 defaults to byte-arrays over Unicode strings:
  181. .. code-block:: pycon
  182. >>> import msgpack
  183. >>> msgpack.unpackb(msgpack.packb([b'spam', u'eggs']))
  184. ['spam', 'eggs']
  185. >>> msgpack.unpackb(msgpack.packb([b'spam', u'eggs'], use_bin_type=True),
  186. raw=False)
  187. ['spam', u'eggs']
  188. This is the same code in Python 3 (same behaviour, but Python 3 has a
  189. different default):
  190. .. code-block:: pycon
  191. >>> import msgpack
  192. >>> msgpack.unpackb(msgpack.packb([b'spam', u'eggs']))
  193. [b'spam', b'eggs']
  194. >>> msgpack.unpackb(msgpack.packb([b'spam', u'eggs'], use_bin_type=True),
  195. raw=False)
  196. [b'spam', 'eggs']
  197. ext type
  198. ^^^^^^^^
  199. To use the **ext** type, pass ``msgpack.ExtType`` object to packer.
  200. .. code-block:: pycon
  201. >>> import msgpack
  202. >>> packed = msgpack.packb(msgpack.ExtType(42, b'xyzzy'))
  203. >>> msgpack.unpackb(packed)
  204. ExtType(code=42, data='xyzzy')
  205. You can use it with ``default`` and ``ext_hook``. See below.
  206. Note about performance
  207. ----------------------
  208. GC
  209. ^^
  210. CPython's GC starts when growing allocated object.
  211. This means unpacking may cause useless GC.
  212. You can use ``gc.disable()`` when unpacking large message.
  213. use_list option
  214. ^^^^^^^^^^^^^^^
  215. List is the default sequence type of Python.
  216. But tuple is lighter than list.
  217. You can use ``use_list=False`` while unpacking when performance is important.
  218. Python's dict can't use list as key and MessagePack allows array for key of mapping.
  219. ``use_list=False`` allows unpacking such message.
  220. Another way to unpacking such object is using ``object_pairs_hook``.
  221. Development
  222. -----------
  223. Test
  224. ^^^^
  225. MessagePack uses `pytest` for testing.
  226. Run test with following command:
  227. $ make test
  228. ..
  229. vim: filetype=rst