python:在django shell中腌制的行为与python shell相反?
作为一个额外的问题源于我的上一个问题,事实证明,与python shell相比,django shell中的泡菜行为不同。
As an additional question stemming from my previous question it turns out that pickle behaves differently in django shell compared to python shell...
此脚本:
import pickle
class TestObj(object): pass
testobj = TestObj()
pickled = pickle.dumps(testobj, pickle.HIGHEST_PROTOCOL)
可以在python shell中正常工作,但在django shell将沿着行提取一个
PickleError
PicklingError:无法打开< class'TestObj'> ;:属性查找__builtin __。TestObj失败
will work fine in python shell, but in django shell will raise a PickleError
along the lines of PicklingError: Can't pickle <class 'TestObj'>: attribute lookup __builtin__.TestObj failed
有人能解释这个问题吗?如果可能,请将其链接回我以前的问题?
Is anyone able to explain the issue here? and if possible, link it back to my previous question?
pickle
将确保它可以重新导入一个类,因为只有实例本身的数据被打了,加上类的导入位置。因此, pickle
在类上查找 __ module __
属性,以确定它来自哪里。
pickle
will make sure it can re-import a class, as only the data on the instance itself is pickled, plus the import location of the class. As such, pickle
looks for the __module__
attribute on the class to determine where it came from.
似乎Django交互式环境不设置 __ module __
属性;因此 TestObj .__ module __
是继承自对象
的基类,而这是 __ builtin__
。也许没有设置 __ name __
global。因此, pickle
模块最终会在您的课堂上找错位置。没有 __ builtin __。TestObj
毕竟。
It appears the Django interactive environment does not set this __module__
attribute; as a result TestObj.__module__
is inherited from the object
base class instead, and that's __builtin__
. Perhaps no __name__
global is set. As a result, the pickle
module ends up looking in the wrong place for your class. There is no __builtin__.TestObj
after all.
从评论中我收集到你正在尝试存储嘲笑Django缓存中的对象。这将不起作用,因为模拟对象不可挑剔。这是有道理的,就像在 (可能是一个全新的Python进程)一样, pickle
知道什么原始类被嘲笑?
From the comments, I gather that you are trying to store mocked objects in the Django cache. That won't work, as mock objects are not pickleable. That makes sense, as on unpickling (which could be in an entirely new Python process), how would pickle
know what original class was being mocked?