Add pickle support to the MSGPackModernSerializer - if a type can't be serialized to native MessagePack, then pickle it

This commit is contained in:
Danielle McLean 2018-06-08 14:46:41 +10:00
parent 0860f37ac0
commit 2c90114b9d
Signed by: 00dani
GPG Key ID: 8EB789DDF3ABD240
1 changed files with 15 additions and 2 deletions

View File

@ -1,11 +1,24 @@
import msgpack
import pickle
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):
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):
return msgpack.unpackb(value, raw=False)
return msgpack.unpackb(value, ext_hook=ext_hook, raw=False)