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.

359 lines
10 KiB

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