东西是令人费解的我有点...在测试过程中,Pickle无法在django locmem缓存中存储对象?
>>> from django.core.cache import get_cache
>>>
>>> cache = get_cache('django.core.cache.backends.locmem.LocMemCache')
>>>
>>> # Set the 'content' cache key to a string
>>> cache.set('content', 'a string')
>>> cache.get('content')
'a string'
>>>
>>> class TestObj(object):
... pass
>>>
>>> a = TestObj()
>>> cache.set('content', a)
>>>
>>> # cache hasn't updated...
>>> cache.get('content')
'a string'
>>>
>>> cache.set('content', 1)
>>> # this is fine however..
>>> cache.get('content')
1
>>>
好了,所以缓存不接受某种原因的对象。
# in locmem.py, set() method
try:
pickled = pickle.dumps(new_value, pickle.HIGHEST_PROTOCOL)
self._cache[key] = pickled
except pickle.PickleError:
pass
这将是为什么,这显然击中PickleError
>>> import pickle
>>> pickled = pickle.dumps(a, pickle.HIGHEST_PROTOCOL)
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/usr/lib/python2.7/pickle.py", line 1374, in dumps
Pickler(file, protocol).dump(obj)
File "/usr/lib/python2.7/pickle.py", line 224, in dump
self.save(obj)
File "/usr/lib/python2.7/pickle.py", line 331, in save
self.save_reduce(obj=obj, *rv)
File "/usr/lib/python2.7/pickle.py", line 396, in save_reduce
save(cls)
File "/usr/lib/python2.7/pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "/usr/lib/python2.7/pickle.py", line 748, in save_global
(obj, module, name))
PicklingError: Can't pickle <class 'TestObj'>: it's not found as __builtin__.TestObj
没问题,但为什么会出现这种情况?它在python控制台中工作得很好,但不是django shell?
# Works fine in python shell...
>>> import pickle
>>> class TestObj(object):
... pass
...
>>> testobj = TestObj()
>>> pickled = pickle.dumps(testobj, pickle.HIGHEST_PROTOCOL)
>>> pickled
'\x80\x02c__main__\nTestObj\nq\x00)\x81q\x01}q\x02b.'
>>>
出现此问题是因为我试图在缓存中存储Mock()对象以进行测试。不知道我是否以这种错误的方式去...
啊,解释它。谢谢,我错过了。我不认为我可以根据你的解决方案预先腌制对象,因为它是我测试的方法,调用cache.set()而不是我的测试。不过谢谢。 – ptr
对不起,我刚刚在python shell中尝试了这一点,并且在使用'from django.utils.six.moves import cPickle'时没有遇到错误,但是我在django shell中获取了它。那么使用django shell会导致这个错误是什么?我不认为这本质上是一个cPickle问题 – ptr
我不太确定它。但是这种行为的可能原因之一可能是shell中的python版本不同,因为django.utils.six.moves存在于python2和python3之间的兼容性(https://pythonhosted.org/six/#module-six.moves) 。要检查它,你可以在django/core/cache/backends/locmem.py中插入“print pickle .__ file__” –