|
12 | 12 | # Distributed under the terms of the Modified BSD License.
|
13 | 13 | from __future__ import annotations
|
14 | 14 |
|
| 15 | +import functools |
15 | 16 | import hashlib
|
16 | 17 | import hmac
|
17 | 18 | import json
|
@@ -132,15 +133,22 @@ def json_unpacker(s: str | bytes) -> t.Any:
|
132 | 133 | _default_packer_unpacker = "json", "json"
|
133 | 134 | _default_pack_unpack = (json_packer, json_unpacker)
|
134 | 135 | else:
|
135 |
| - import functools |
136 |
| - |
137 | 136 | orjson_packer = functools.partial(
|
138 | 137 | orjson.dumps, default=json_default, option=orjson.OPT_NAIVE_UTC | orjson.OPT_UTC_Z
|
139 | 138 | )
|
140 | 139 | orjson_unpacker = orjson.loads
|
141 | 140 | _default_packer_unpacker = "orjson", "orjson"
|
142 | 141 | _default_pack_unpack = (orjson_packer, orjson_unpacker)
|
143 | 142 |
|
| 143 | +try: |
| 144 | + import msgpack # type:ignore[import-not-found] |
| 145 | + |
| 146 | +except ModuleNotFoundError: |
| 147 | + msgpack = None |
| 148 | +else: |
| 149 | + msgpack_packer = functools.partial(msgpack.packb, default=json_default) |
| 150 | + msgpack_unpacker = msgpack.unpackb |
| 151 | + |
144 | 152 |
|
145 | 153 | def pickle_packer(o: t.Any) -> bytes:
|
146 | 154 | """Pack an object using the pickle module."""
|
@@ -331,7 +339,7 @@ class Session(Configurable):
|
331 | 339 |
|
332 | 340 | debug : bool
|
333 | 341 | whether to trigger extra debugging statements
|
334 |
| - packer/unpacker : str : 'json', 'pickle' or import_string |
| 342 | + packer/unpacker : str : 'orjson', 'json', 'pickle', 'msgpack' or import_string |
335 | 343 | importstrings for methods to serialize message parts. If just
|
336 | 344 | 'json' or 'pickle', predefined JSON and pickle packers will be used.
|
337 | 345 | Otherwise, the entire importstring must be used.
|
@@ -399,6 +407,10 @@ def _packer_unpacker_changed(self, change: t.Any) -> None:
|
399 | 407 | self.pack = pickle_packer
|
400 | 408 | self.unpack = pickle_unpacker
|
401 | 409 | self.packer = self.unpacker = new
|
| 410 | + elif new_ == "msgpack": |
| 411 | + self.pack = msgpack_packer |
| 412 | + self.unpack = msgpack_unpacker |
| 413 | + self.packer = self.unpacker = new |
402 | 414 | else:
|
403 | 415 | obj = import_item(str(new))
|
404 | 416 | name = "pack" if change["name"] == "packer" else "unpack"
|
@@ -523,7 +535,7 @@ def __init__(self, **kwargs: t.Any) -> None:
|
523 | 535 |
|
524 | 536 | debug : bool
|
525 | 537 | whether to trigger extra debugging statements
|
526 |
| - packer/unpacker : str : 'json', 'pickle' or import_string |
| 538 | + packer/unpacker : str : 'orjson', 'json', 'pickle', 'msgpack' or import_string |
527 | 539 | importstrings for methods to serialize message parts. If just
|
528 | 540 | 'json' or 'pickle', predefined JSON and pickle packers will be used.
|
529 | 541 | Otherwise, the entire importstring must be used.
|
|
0 commit comments