Add pickle support to the MSGPackModernSerializer - if a type can't be serialized to native MessagePack, then pickle it
This commit is contained in:
parent
0860f37ac0
commit
2c90114b9d
1 changed files with 15 additions and 2 deletions
|
@ -1,11 +1,24 @@
|
||||||
import msgpack
|
import msgpack
|
||||||
|
import pickle
|
||||||
|
|
||||||
from django_redis.serializers.base import BaseSerializer
|
from django_redis.serializers.base import BaseSerializer
|
||||||
|
|
||||||
|
|
||||||
|
def default(obj):
|
||||||
|
# Pickle anything that MessagePack can't handle itself.
|
||||||
|
return msgpack.ExtType(69, pickle.dumps(obj, protocol=4))
|
||||||
|
|
||||||
|
|
||||||
|
def ext_hook(code, data):
|
||||||
|
# Unpickle if we pickled - otherwise do nothing.
|
||||||
|
if code == 69:
|
||||||
|
return pickle.loads(data)
|
||||||
|
return msgpack.ExtType(code, data)
|
||||||
|
|
||||||
|
|
||||||
class MSGPackModernSerializer(BaseSerializer):
|
class MSGPackModernSerializer(BaseSerializer):
|
||||||
def dumps(self, value):
|
def dumps(self, value):
|
||||||
return msgpack.packb(value, use_bin_type=True)
|
return msgpack.packb(value, default=default, use_bin_type=True)
|
||||||
|
|
||||||
def loads(self, value):
|
def loads(self, value):
|
||||||
return msgpack.unpackb(value, raw=False)
|
return msgpack.unpackb(value, ext_hook=ext_hook, raw=False)
|
||||||
|
|
Loading…
Reference in a new issue