我正在使用自定义pickler,根据Shane Hathaway的代码,将任何不可腌制的对象(例如套接字或文件)替换为它们的字符串表示形式: Python: Pickling a dict with some unpicklable items
它在大多数情况下都有效,但是当我尝试取消 Django HttpResponse 时,我收到以下错误:UnpicklingError: NEWOBJ class argument is not a type object
我不知道错误的实际含义。如果可以腌制,为什么不能解开?我在 Google 上找到了三个对这个错误的引用,但没有真正解释它发生的原因或如何修复它。
这是我的代码:
from cPickle import Pickler, Unpickler, UnpicklingError
class FilteredObject:
def __init__(self, about):
self.about = about
def __repr__(self):
return 'FilteredObject(%s)' % repr(self.about)
class MyPickler(object):
def __init__(self, file, protocol=2):
pickler = Pickler(file, protocol)
pickler.persistent_id = self.persistent_id
self.dump = pickler.dump
self.clear_memo = pickler.clear_memo
def persistent_id(self, obj):
if not hasattr(obj, '__getstate__') and not isinstance(obj,
(basestring, bool, int, long, float, complex, tuple, list, set, dict)):
return ["filtered:%s" % str(obj)]
else:
return None
class MyUnpickler(object):
def __init__(self, file):
unpickler = Unpickler(file)
unpickler.persistent_load = self.persistent_load
self.load = unpickler.load
self.noload = unpickler.noload
def persistent_load(self, obj_id):
if obj_id[0].startswith('filtered:'):
return FilteredObject(obj_id[0][9:])
else:
raise UnpicklingError('Invalid persistent id')
###### serialize to file
f = open('test.txt','wb')
p = MyPickler(f)
p.dump(data)
f.close()
###### unserialize from file
f = open('test.txt','rb')
pickled_data = f.read()
f.seek(0)
u = MyUnpickler(f)
data = u.load()