b10-msgpack-numpy 0.4.8__py2.py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- b10_msgpack_numpy-0.4.8.dist-info/METADATA +163 -0
- b10_msgpack_numpy-0.4.8.dist-info/RECORD +7 -0
- b10_msgpack_numpy-0.4.8.dist-info/WHEEL +6 -0
- b10_msgpack_numpy-0.4.8.dist-info/licenses/AUTHORS.md +18 -0
- b10_msgpack_numpy-0.4.8.dist-info/licenses/LICENSE.md +35 -0
- b10_msgpack_numpy-0.4.8.dist-info/top_level.txt +1 -0
- msgpack_numpy.py +343 -0
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: b10-msgpack-numpy
|
|
3
|
+
Version: 0.4.8
|
|
4
|
+
Summary: Numpy data serialization using msgpack (Baseten fork with CWE-502 fix)
|
|
5
|
+
Home-page: https://github.com/basetenlabs/b10-msgpack-numpy
|
|
6
|
+
Author: Lev E. Givon
|
|
7
|
+
Author-email: lev@columbia.edu
|
|
8
|
+
License: BSD
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Intended Audience :: Science/Research
|
|
12
|
+
Classifier: License :: OSI Approved :: BSD License
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python
|
|
15
|
+
Classifier: Programming Language :: Python :: 2.7
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.4
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.5
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.6
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.7
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
22
|
+
Classifier: Topic :: Scientific/Engineering
|
|
23
|
+
Classifier: Topic :: Software Development
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
License-File: LICENSE.md
|
|
26
|
+
License-File: AUTHORS.md
|
|
27
|
+
Requires-Dist: numpy>=1.9.0
|
|
28
|
+
Requires-Dist: msgpack>=0.5.2
|
|
29
|
+
Dynamic: author
|
|
30
|
+
Dynamic: author-email
|
|
31
|
+
Dynamic: classifier
|
|
32
|
+
Dynamic: description
|
|
33
|
+
Dynamic: description-content-type
|
|
34
|
+
Dynamic: home-page
|
|
35
|
+
Dynamic: license
|
|
36
|
+
Dynamic: license-file
|
|
37
|
+
Dynamic: requires-dist
|
|
38
|
+
Dynamic: summary
|
|
39
|
+
|
|
40
|
+
Package Description
|
|
41
|
+
-------------------
|
|
42
|
+
This package provides encoding and decoding routines that enable the
|
|
43
|
+
serialization and deserialization of numerical and array data types provided by
|
|
44
|
+
[numpy](http://www.numpy.org/) using the highly efficient
|
|
45
|
+
[msgpack](http://msgpack.org/) format. Serialization of Python's
|
|
46
|
+
native complex data types is also supported.
|
|
47
|
+
|
|
48
|
+
[](https://pypi.python.org/pypi/msgpack-numpy)
|
|
49
|
+
[](https://travis-ci.org/lebedov/msgpack-numpy)
|
|
50
|
+
|
|
51
|
+
Installation
|
|
52
|
+
------------
|
|
53
|
+
msgpack-numpy requires msgpack-python and numpy. If you
|
|
54
|
+
have [pip](http://www.pip-installer.org/) installed on your
|
|
55
|
+
system, run
|
|
56
|
+
|
|
57
|
+
pip install msgpack-numpy
|
|
58
|
+
|
|
59
|
+
to install the package and all dependencies. You can also download
|
|
60
|
+
the source tarball, unpack it, and run
|
|
61
|
+
|
|
62
|
+
python setup.py install
|
|
63
|
+
|
|
64
|
+
from within the source directory.
|
|
65
|
+
|
|
66
|
+
Usage
|
|
67
|
+
-----
|
|
68
|
+
The easiest way to use msgpack-numpy is to call its monkey patching
|
|
69
|
+
function after importing the Python msgpack package:
|
|
70
|
+
|
|
71
|
+
import msgpack
|
|
72
|
+
import msgpack_numpy as m
|
|
73
|
+
m.patch()
|
|
74
|
+
|
|
75
|
+
This will automatically force all msgpack serialization and deserialization
|
|
76
|
+
routines (and other packages that use them) to become numpy-aware.
|
|
77
|
+
Of course, one can also manually pass the encoder and
|
|
78
|
+
decoder provided by msgpack-numpy to the msgpack routines:
|
|
79
|
+
|
|
80
|
+
import msgpack
|
|
81
|
+
import msgpack_numpy as m
|
|
82
|
+
import numpy as np
|
|
83
|
+
|
|
84
|
+
x = np.random.rand(5)
|
|
85
|
+
x_enc = msgpack.packb(x, default=m.encode)
|
|
86
|
+
x_rec = msgpack.unpackb(x_enc, object_hook=m.decode)
|
|
87
|
+
|
|
88
|
+
msgpack-numpy will try to use the binary (fast) extension in msgpack by default.
|
|
89
|
+
If msgpack was not compiled with Cython (or if the ``MSGPACK_PUREPYTHON``
|
|
90
|
+
variable is set), it will fall back to using the slower pure Python msgpack
|
|
91
|
+
implementation.
|
|
92
|
+
|
|
93
|
+
Notes
|
|
94
|
+
-----
|
|
95
|
+
The primary design goal of msgpack-numpy is ensuring preservation of numerical
|
|
96
|
+
data types during msgpack serialization and deserialization. Inclusion of type
|
|
97
|
+
information in the serialized data necessarily incurs some storage overhead; if
|
|
98
|
+
preservation of type information is not needed, one may be able to avoid some
|
|
99
|
+
of this overhead by writing a custom encoder/decoder pair that produces more
|
|
100
|
+
efficient serializations for those specific use cases.
|
|
101
|
+
|
|
102
|
+
Numpy arrays with a dtype of 'O' are serialized using pickle as a fallback
|
|
103
|
+
solution. Deserializing them requires unpickling, which executes arbitrary
|
|
104
|
+
code from the payload, so decoding is **disabled by default** (CWE-502):
|
|
105
|
+
``decode``, ``unpackb``/``unpack`` and ``Unpacker`` raise
|
|
106
|
+
``msgpack_numpy.PickleNotAllowed`` when they encounter an object-dtype array.
|
|
107
|
+
If you control both ends, opt in explicitly:
|
|
108
|
+
|
|
109
|
+
x_rec = msgpack.unpackb(x_enc, allow_pickle=True)
|
|
110
|
+
|
|
111
|
+
Never enable ``allow_pickle`` for untrusted input. As the overhead of pickle
|
|
112
|
+
serialization negates one of the reasons to use msgpack, consider writing a
|
|
113
|
+
custom encoder/decoder for your specific use case instead.
|
|
114
|
+
|
|
115
|
+
Note that numpy arrays deserialized by msgpack-numpy are read-only and must be copied
|
|
116
|
+
if they are to be modified.
|
|
117
|
+
|
|
118
|
+
Development
|
|
119
|
+
-----------
|
|
120
|
+
The latest source code can be obtained from
|
|
121
|
+
[GitHub](https://github.com/basetenlabs/b10-msgpack-numpy/). This is the Baseten
|
|
122
|
+
fork of [lebedov/msgpack-numpy](https://github.com/lebedov/msgpack-numpy); the
|
|
123
|
+
distribution is named ``b10-msgpack-numpy`` and still provides the
|
|
124
|
+
``msgpack_numpy`` module.
|
|
125
|
+
|
|
126
|
+
msgpack-numpy maintains compatibility with python versions 2.7 and 3.5+.
|
|
127
|
+
|
|
128
|
+
Install [`tox`](https://tox.readthedocs.io/en/latest/) to support testing
|
|
129
|
+
across multiple python versions in your development environment. If you
|
|
130
|
+
use [`conda`](https://docs.conda.io/en/latest/) to install `python` use
|
|
131
|
+
[`tox-conda`](https://github.com/tox-dev/tox-conda) to automatically manage
|
|
132
|
+
testing across all supported python versions.
|
|
133
|
+
|
|
134
|
+
# Using a system python
|
|
135
|
+
pip install tox
|
|
136
|
+
|
|
137
|
+
# Additionally, using a conda-provided python
|
|
138
|
+
pip install tox tox-conda
|
|
139
|
+
|
|
140
|
+
Execute tests across supported python versions:
|
|
141
|
+
|
|
142
|
+
tox
|
|
143
|
+
|
|
144
|
+
Authors
|
|
145
|
+
-------
|
|
146
|
+
See the included [AUTHORS.md](https://github.com/lebedov/msgpack-numpy/blob/master/AUTHORS.md) file for
|
|
147
|
+
more information.
|
|
148
|
+
|
|
149
|
+
License
|
|
150
|
+
-------
|
|
151
|
+
This software is licensed under the [BSD License](http://www.opensource.org/licenses/bsd-license).
|
|
152
|
+
See the included [LICENSE.md](https://github.com/lebedov/msgpack-numpy/blob/master/LICENSE.md) file for
|
|
153
|
+
more information.
|
|
154
|
+
|
|
155
|
+
See Also
|
|
156
|
+
--------
|
|
157
|
+
[msgpack-numpy-js](https://github.com/emerald-geomodelling/msgpack-numpy-js) by
|
|
158
|
+
[Egil Möller](https://github.com/redhog) is a JavaScript library that can
|
|
159
|
+
serialize and deserialize JS typed arrays with msgpack.
|
|
160
|
+
|
|
161
|
+
[msgpack-numpy-rs](https://github.com/clearviewai/msgpack-numpy-rs) by [
|
|
162
|
+
Terrence Liu](https://github.com/terencezl) is a Rust crate (mostly) compatible with msgpack-numpy
|
|
163
|
+
that can serialize and deserialize numpy arrays with msgpack.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
msgpack_numpy.py,sha256=V81ZsmKczgTtb819qbr1Y-frkO4bLvqk3OMlmYPAjRo,13626
|
|
2
|
+
b10_msgpack_numpy-0.4.8.dist-info/licenses/AUTHORS.md,sha256=X-BEbd1tHHD6KYdHNoWC3B2Rwj1iyPtyKFlbyH_VMjI,745
|
|
3
|
+
b10_msgpack_numpy-0.4.8.dist-info/licenses/LICENSE.md,sha256=UJqnrxmuK1sWgbIrlpYn7p4f0V_36lv59uMB_ETVpsI,1551
|
|
4
|
+
b10_msgpack_numpy-0.4.8.dist-info/METADATA,sha256=Tz-4VejGI2ALyDTxvLTosiG-ytcX9wXOUT5m_B0EeEo,6240
|
|
5
|
+
b10_msgpack_numpy-0.4.8.dist-info/WHEEL,sha256=Uvlg2aNlEKdilsyFSJt1QX5me0eEbCjQzR3nZeFkvy4,109
|
|
6
|
+
b10_msgpack_numpy-0.4.8.dist-info/top_level.txt,sha256=GdppitFJC93hx_GPq6zrJiWq9Is2TU3XrUBMfl7tdbk,14
|
|
7
|
+
b10_msgpack_numpy-0.4.8.dist-info/RECORD,,
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
<!---
|
|
2
|
+
-*- mode:markdown -*-
|
|
3
|
+
vi:ft=markdown
|
|
4
|
+
-->
|
|
5
|
+
|
|
6
|
+
Authors
|
|
7
|
+
=======
|
|
8
|
+
This software was written and packaged by [Lev E. Givon](https://github.com/lebedov)
|
|
9
|
+
|
|
10
|
+
Special thanks are due to the following parties for their contributions:
|
|
11
|
+
|
|
12
|
+
- [Alex Ford](https://github.com/asford) - bug fix.
|
|
13
|
+
- [Colin Jermain](https://github.com/cjermain) - Python 3 support.
|
|
14
|
+
- [Etienne Wodey](https://github.com/airwoodix) - support for ndarrays with dtype='O'
|
|
15
|
+
- [John Tyree](https://github.com/johntyree) - support for numpy scalar booleans.
|
|
16
|
+
- [Mehdi Sadeghi](https://github.com/mehdisadeghi) - bug reports.
|
|
17
|
+
- [Sujoy Roy](https://github.com/tvkpz) - bug reports.
|
|
18
|
+
- [Jose Coutinho](https://github.com/tiagocoutinho) - make msgpack-numpy params consistent with msgpack-python.
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
<!---
|
|
2
|
+
-*- mode:markdown -*-
|
|
3
|
+
vi:ft=markdown
|
|
4
|
+
-->
|
|
5
|
+
License
|
|
6
|
+
=======
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2013-2022, Lev E. Givon.
|
|
9
|
+
All rights reserved.
|
|
10
|
+
|
|
11
|
+
Redistribution and use in source and binary forms, with or without
|
|
12
|
+
modification, are permitted provided that the following conditions are
|
|
13
|
+
met:
|
|
14
|
+
|
|
15
|
+
* Redistributions of source code must retain the above copyright
|
|
16
|
+
notice, this list of conditions and the following disclaimer.
|
|
17
|
+
* Redistributions in binary form must reproduce the above
|
|
18
|
+
copyright notice, this list of conditions and the following
|
|
19
|
+
disclaimer in the documentation and/or other materials provided
|
|
20
|
+
with the distribution.
|
|
21
|
+
* Neither the name of Lev E. Givon nor the names of any
|
|
22
|
+
contributors may be used to endorse or promote products derived
|
|
23
|
+
from this software without specific prior written permission.
|
|
24
|
+
|
|
25
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
|
26
|
+
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
|
27
|
+
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
|
28
|
+
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
|
29
|
+
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
|
30
|
+
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
|
31
|
+
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
|
32
|
+
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
|
33
|
+
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
34
|
+
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
35
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
msgpack_numpy
|
msgpack_numpy.py
ADDED
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
|
|
3
|
+
"""
|
|
4
|
+
Support for serialization of numpy data types with msgpack.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
# Copyright (c) 2013-2022, Lev E. Givon
|
|
8
|
+
# All rights reserved.
|
|
9
|
+
# Distributed under the terms of the BSD license:
|
|
10
|
+
# http://www.opensource.org/licenses/bsd-license
|
|
11
|
+
|
|
12
|
+
import sys
|
|
13
|
+
import functools
|
|
14
|
+
import pickle
|
|
15
|
+
import warnings
|
|
16
|
+
|
|
17
|
+
import msgpack
|
|
18
|
+
from msgpack import Packer as _Packer, Unpacker as _Unpacker, \
|
|
19
|
+
unpack as _unpack, unpackb as _unpackb
|
|
20
|
+
import numpy as np
|
|
21
|
+
|
|
22
|
+
if sys.version_info >= (3, 0):
|
|
23
|
+
def ndarray_to_bytes(obj):
|
|
24
|
+
if obj.dtype == 'O':
|
|
25
|
+
return obj.dumps()
|
|
26
|
+
else:
|
|
27
|
+
if sys.platform == 'darwin':
|
|
28
|
+
return obj.tobytes()
|
|
29
|
+
else:
|
|
30
|
+
return obj.data if obj.flags['C_CONTIGUOUS'] else obj.tobytes()
|
|
31
|
+
|
|
32
|
+
num_to_bytes = lambda obj: obj.data
|
|
33
|
+
|
|
34
|
+
def tostr(x):
|
|
35
|
+
if isinstance(x, bytes):
|
|
36
|
+
return x.decode()
|
|
37
|
+
else:
|
|
38
|
+
return str(x)
|
|
39
|
+
else:
|
|
40
|
+
def ndarray_to_bytes(obj):
|
|
41
|
+
if obj.dtype == 'O':
|
|
42
|
+
return obj.dumps()
|
|
43
|
+
else:
|
|
44
|
+
if sys.platform == 'darwin':
|
|
45
|
+
return obj.tobytes()
|
|
46
|
+
else:
|
|
47
|
+
return memoryview(obj.data) if obj.flags['C_CONTIGUOUS'] else obj.tobytes()
|
|
48
|
+
|
|
49
|
+
num_to_bytes = lambda obj: memoryview(obj.data)
|
|
50
|
+
|
|
51
|
+
def tostr(x):
|
|
52
|
+
return x
|
|
53
|
+
|
|
54
|
+
def encode(obj, chain=None):
|
|
55
|
+
"""
|
|
56
|
+
Data encoder for serializing numpy data types.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
if isinstance(obj, np.ndarray):
|
|
60
|
+
# If the dtype is structured, store the interface description;
|
|
61
|
+
# otherwise, store the corresponding array protocol type string:
|
|
62
|
+
if obj.dtype.kind in ('V', 'O'):
|
|
63
|
+
kind = bytes(obj.dtype.kind, 'ascii')
|
|
64
|
+
descr = obj.dtype.descr
|
|
65
|
+
else:
|
|
66
|
+
kind = b''
|
|
67
|
+
descr = obj.dtype.str
|
|
68
|
+
|
|
69
|
+
return {b'nd': True,
|
|
70
|
+
b'type': descr,
|
|
71
|
+
b'kind': kind,
|
|
72
|
+
b'shape': obj.shape,
|
|
73
|
+
b'data': ndarray_to_bytes(obj)}
|
|
74
|
+
elif isinstance(obj, (np.bool_, np.number)):
|
|
75
|
+
return {b'nd': False,
|
|
76
|
+
b'type': obj.dtype.str,
|
|
77
|
+
b'data': num_to_bytes(obj)}
|
|
78
|
+
elif isinstance(obj, complex):
|
|
79
|
+
return {b'complex': True,
|
|
80
|
+
b'data': obj.__repr__()}
|
|
81
|
+
else:
|
|
82
|
+
return obj if chain is None else chain(obj)
|
|
83
|
+
|
|
84
|
+
class PickleNotAllowed(ValueError):
|
|
85
|
+
"""
|
|
86
|
+
Raised when an object-dtype ndarray would require unpickling and
|
|
87
|
+
``allow_pickle`` is ``False`` (the default).
|
|
88
|
+
|
|
89
|
+
Object-dtype arrays are serialized by pickle, so deserializing them
|
|
90
|
+
executes arbitrary code from the payload. Never enable ``allow_pickle``
|
|
91
|
+
for data that was not produced by a trusted encoder.
|
|
92
|
+
"""
|
|
93
|
+
|
|
94
|
+
def decode(obj, chain=None, allow_pickle=False):
|
|
95
|
+
"""
|
|
96
|
+
Decoder for deserializing numpy data types.
|
|
97
|
+
|
|
98
|
+
:param obj: The decoded msgpack object.
|
|
99
|
+
:param chain: Optional next decoder in the chain, called for objects
|
|
100
|
+
that this decoder does not recognize.
|
|
101
|
+
:param allow_pickle: Whether to unpickle object-dtype ndarrays. This is
|
|
102
|
+
disabled by default because unpickling untrusted data allows
|
|
103
|
+
arbitrary code execution (CWE-502). Only set this to ``True`` for
|
|
104
|
+
payloads you produced yourself.
|
|
105
|
+
:raises PickleNotAllowed: If an object-dtype ndarray is encountered and
|
|
106
|
+
``allow_pickle`` is ``False``.
|
|
107
|
+
"""
|
|
108
|
+
|
|
109
|
+
try:
|
|
110
|
+
if b'nd' in obj:
|
|
111
|
+
if obj[b'nd'] is True:
|
|
112
|
+
|
|
113
|
+
# Check if b'kind' is in obj to enable decoding of data
|
|
114
|
+
# serialized with older versions (#20) or data
|
|
115
|
+
# that had dtype == 'O' (#46):
|
|
116
|
+
if b'kind' in obj and obj[b'kind'] == b'V':
|
|
117
|
+
descr = [tuple(tostr(t) if type(t) is bytes else t for t in d) \
|
|
118
|
+
for d in obj[b'type']]
|
|
119
|
+
elif b'kind' in obj and obj[b'kind'] == b'O':
|
|
120
|
+
if not allow_pickle:
|
|
121
|
+
raise PickleNotAllowed(
|
|
122
|
+
'refusing to unpickle an object-dtype ndarray; '
|
|
123
|
+
'pass allow_pickle=True (decode/unpackb/Unpacker) '
|
|
124
|
+
'to opt in for trusted payloads only')
|
|
125
|
+
return pickle.loads(obj[b'data'])
|
|
126
|
+
else:
|
|
127
|
+
descr = obj[b'type']
|
|
128
|
+
return np.ndarray(buffer=obj[b'data'],
|
|
129
|
+
dtype=_unpack_dtype(descr),
|
|
130
|
+
shape=obj[b'shape'])
|
|
131
|
+
else:
|
|
132
|
+
descr = obj[b'type']
|
|
133
|
+
return np.frombuffer(obj[b'data'],
|
|
134
|
+
dtype=_unpack_dtype(descr))[0]
|
|
135
|
+
elif b'complex' in obj:
|
|
136
|
+
return complex(tostr(obj[b'data']))
|
|
137
|
+
else:
|
|
138
|
+
return obj if chain is None else chain(obj)
|
|
139
|
+
except KeyError:
|
|
140
|
+
return obj if chain is None else chain(obj)
|
|
141
|
+
|
|
142
|
+
def _unpack_dtype(dtype):
|
|
143
|
+
"""
|
|
144
|
+
Unpack dtype descr, recursively unpacking nested structured dtypes.
|
|
145
|
+
"""
|
|
146
|
+
|
|
147
|
+
if isinstance(dtype, (list, tuple)):
|
|
148
|
+
# Unpack structured dtypes of the form: (name, type, *shape)
|
|
149
|
+
dtype = [
|
|
150
|
+
(subdtype[0], _unpack_dtype(subdtype[1])) + tuple(subdtype[2:])
|
|
151
|
+
for subdtype in dtype
|
|
152
|
+
]
|
|
153
|
+
return np.dtype(dtype)
|
|
154
|
+
|
|
155
|
+
if msgpack.version < (1, 0, 0):
|
|
156
|
+
warnings.warn('support for msgpack < 1.0.0 will be removed in a future release',
|
|
157
|
+
DeprecationWarning)
|
|
158
|
+
|
|
159
|
+
# Maintain support for msgpack < 0.4.0:
|
|
160
|
+
if msgpack.version < (0, 4, 0):
|
|
161
|
+
class Packer(_Packer):
|
|
162
|
+
def __init__(self, default=None,
|
|
163
|
+
encoding='utf-8',
|
|
164
|
+
unicode_errors='strict',
|
|
165
|
+
use_single_float=False,
|
|
166
|
+
autoreset=1):
|
|
167
|
+
default = functools.partial(encode, chain=default)
|
|
168
|
+
super(Packer, self).__init__(default=default,
|
|
169
|
+
encoding=encoding,
|
|
170
|
+
unicode_errors=unicode_errors,
|
|
171
|
+
use_single_float=use_single_float,
|
|
172
|
+
autoreset=autoreset)
|
|
173
|
+
class Unpacker(_Unpacker):
|
|
174
|
+
def __init__(self, file_like=None, read_size=0, use_list=None,
|
|
175
|
+
object_hook=None,
|
|
176
|
+
object_pairs_hook=None, list_hook=None, encoding='utf-8',
|
|
177
|
+
unicode_errors='strict', max_buffer_size=0,
|
|
178
|
+
allow_pickle=False):
|
|
179
|
+
object_hook = functools.partial(decode, chain=object_hook,
|
|
180
|
+
allow_pickle=allow_pickle)
|
|
181
|
+
super(Unpacker, self).__init__(file_like=file_like,
|
|
182
|
+
read_size=read_size,
|
|
183
|
+
use_list=use_list,
|
|
184
|
+
object_hook=object_hook,
|
|
185
|
+
object_pairs_hook=object_pairs_hook,
|
|
186
|
+
list_hook=list_hook,
|
|
187
|
+
encoding=encoding,
|
|
188
|
+
unicode_errors=unicode_errors,
|
|
189
|
+
max_buffer_size=max_buffer_size)
|
|
190
|
+
|
|
191
|
+
elif msgpack.version < (1, 0, 0):
|
|
192
|
+
class Packer(_Packer):
|
|
193
|
+
def __init__(self, default=None,
|
|
194
|
+
unicode_errors='strict',
|
|
195
|
+
use_single_float=False,
|
|
196
|
+
autoreset=1,
|
|
197
|
+
use_bin_type=True,
|
|
198
|
+
strict_types=False):
|
|
199
|
+
default = functools.partial(encode, chain=default)
|
|
200
|
+
super(Packer, self).__init__(default=default,
|
|
201
|
+
unicode_errors=unicode_errors,
|
|
202
|
+
use_single_float=use_single_float,
|
|
203
|
+
autoreset=autoreset,
|
|
204
|
+
use_bin_type=use_bin_type,
|
|
205
|
+
strict_types=strict_types)
|
|
206
|
+
|
|
207
|
+
class Unpacker(_Unpacker):
|
|
208
|
+
def __init__(self, file_like=None, read_size=0, use_list=None,
|
|
209
|
+
raw=False,
|
|
210
|
+
object_hook=None,
|
|
211
|
+
object_pairs_hook=None, list_hook=None,
|
|
212
|
+
unicode_errors='strict', max_buffer_size=0,
|
|
213
|
+
ext_hook=msgpack.ExtType,
|
|
214
|
+
allow_pickle=False):
|
|
215
|
+
object_hook = functools.partial(decode, chain=object_hook,
|
|
216
|
+
allow_pickle=allow_pickle)
|
|
217
|
+
super(Unpacker, self).__init__(file_like=file_like,
|
|
218
|
+
read_size=read_size,
|
|
219
|
+
use_list=use_list,
|
|
220
|
+
raw=raw,
|
|
221
|
+
object_hook=object_hook,
|
|
222
|
+
object_pairs_hook=object_pairs_hook,
|
|
223
|
+
list_hook=list_hook,
|
|
224
|
+
unicode_errors=unicode_errors,
|
|
225
|
+
max_buffer_size=max_buffer_size,
|
|
226
|
+
ext_hook=ext_hook)
|
|
227
|
+
|
|
228
|
+
else:
|
|
229
|
+
class Packer(_Packer):
|
|
230
|
+
def __init__(self,
|
|
231
|
+
default=None,
|
|
232
|
+
use_single_float=False,
|
|
233
|
+
autoreset=True,
|
|
234
|
+
use_bin_type=True,
|
|
235
|
+
strict_types=False,
|
|
236
|
+
datetime=False,
|
|
237
|
+
unicode_errors=None):
|
|
238
|
+
default = functools.partial(encode, chain=default)
|
|
239
|
+
super(Packer, self).__init__(default=default,
|
|
240
|
+
use_single_float=use_single_float,
|
|
241
|
+
autoreset=autoreset,
|
|
242
|
+
use_bin_type=use_bin_type,
|
|
243
|
+
strict_types=strict_types,
|
|
244
|
+
datetime=datetime,
|
|
245
|
+
unicode_errors=unicode_errors)
|
|
246
|
+
|
|
247
|
+
class Unpacker(_Unpacker):
|
|
248
|
+
def __init__(self,
|
|
249
|
+
file_like=None,
|
|
250
|
+
read_size=0,
|
|
251
|
+
use_list=True,
|
|
252
|
+
raw=False,
|
|
253
|
+
timestamp=0,
|
|
254
|
+
strict_map_key=True,
|
|
255
|
+
object_hook=None,
|
|
256
|
+
object_pairs_hook=None,
|
|
257
|
+
list_hook=None,
|
|
258
|
+
unicode_errors=None,
|
|
259
|
+
max_buffer_size=100 * 1024 * 1024,
|
|
260
|
+
ext_hook=msgpack.ExtType,
|
|
261
|
+
max_str_len=-1,
|
|
262
|
+
max_bin_len=-1,
|
|
263
|
+
max_array_len=-1,
|
|
264
|
+
max_map_len=-1,
|
|
265
|
+
max_ext_len=-1,
|
|
266
|
+
allow_pickle=False):
|
|
267
|
+
object_hook = functools.partial(decode, chain=object_hook,
|
|
268
|
+
allow_pickle=allow_pickle)
|
|
269
|
+
super(Unpacker, self).__init__(file_like=file_like,
|
|
270
|
+
read_size=read_size,
|
|
271
|
+
use_list=use_list,
|
|
272
|
+
raw=raw,
|
|
273
|
+
timestamp=timestamp,
|
|
274
|
+
strict_map_key=strict_map_key,
|
|
275
|
+
object_hook=object_hook,
|
|
276
|
+
object_pairs_hook=object_pairs_hook,
|
|
277
|
+
list_hook=list_hook,
|
|
278
|
+
unicode_errors=unicode_errors,
|
|
279
|
+
max_buffer_size=max_buffer_size,
|
|
280
|
+
ext_hook=ext_hook,
|
|
281
|
+
max_str_len=max_str_len,
|
|
282
|
+
max_bin_len=max_bin_len,
|
|
283
|
+
max_array_len=max_array_len,
|
|
284
|
+
max_map_len=max_map_len,
|
|
285
|
+
max_ext_len=max_ext_len)
|
|
286
|
+
|
|
287
|
+
def pack(o, stream, **kwargs):
|
|
288
|
+
"""
|
|
289
|
+
Pack an object and write it to a stream.
|
|
290
|
+
"""
|
|
291
|
+
|
|
292
|
+
packer = Packer(**kwargs)
|
|
293
|
+
stream.write(packer.pack(o))
|
|
294
|
+
|
|
295
|
+
def packb(o, **kwargs):
|
|
296
|
+
"""
|
|
297
|
+
Pack an object and return the packed bytes.
|
|
298
|
+
"""
|
|
299
|
+
|
|
300
|
+
return Packer(**kwargs).pack(o)
|
|
301
|
+
|
|
302
|
+
def unpack(stream, **kwargs):
|
|
303
|
+
"""
|
|
304
|
+
Unpack a packed object from a stream.
|
|
305
|
+
"""
|
|
306
|
+
|
|
307
|
+
allow_pickle = kwargs.pop('allow_pickle', False)
|
|
308
|
+
object_hook = kwargs.get('object_hook')
|
|
309
|
+
kwargs['object_hook'] = functools.partial(decode, chain=object_hook,
|
|
310
|
+
allow_pickle=allow_pickle)
|
|
311
|
+
return _unpack(stream, **kwargs)
|
|
312
|
+
|
|
313
|
+
def unpackb(packed, **kwargs):
|
|
314
|
+
"""
|
|
315
|
+
Unpack a packed object.
|
|
316
|
+
"""
|
|
317
|
+
|
|
318
|
+
allow_pickle = kwargs.pop('allow_pickle', False)
|
|
319
|
+
object_hook = kwargs.get('object_hook')
|
|
320
|
+
kwargs['object_hook'] = functools.partial(decode, chain=object_hook,
|
|
321
|
+
allow_pickle=allow_pickle)
|
|
322
|
+
return _unpackb(packed, **kwargs)
|
|
323
|
+
|
|
324
|
+
load = unpack
|
|
325
|
+
loads = unpackb
|
|
326
|
+
dump = pack
|
|
327
|
+
dumps = packb
|
|
328
|
+
|
|
329
|
+
def patch():
|
|
330
|
+
"""
|
|
331
|
+
Monkey patch msgpack module to enable support for serializing numpy types.
|
|
332
|
+
"""
|
|
333
|
+
|
|
334
|
+
setattr(msgpack, 'Packer', Packer)
|
|
335
|
+
setattr(msgpack, 'Unpacker', Unpacker)
|
|
336
|
+
setattr(msgpack, 'load', unpack)
|
|
337
|
+
setattr(msgpack, 'loads', unpackb)
|
|
338
|
+
setattr(msgpack, 'dump', pack)
|
|
339
|
+
setattr(msgpack, 'dumps', packb)
|
|
340
|
+
setattr(msgpack, 'pack', pack)
|
|
341
|
+
setattr(msgpack, 'packb', packb)
|
|
342
|
+
setattr(msgpack, 'unpack', unpack)
|
|
343
|
+
setattr(msgpack, 'unpackb', unpackb)
|