python:在django shell中腌制的行为与python shell相反? [英] python: pickle misbehaving in django shell as opposed to python shell?

查看:128
本文介绍了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?

这篇关于python:在django shell中腌制的行为与python shell相反?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆