python : How to read pickle dump?

标签 python sql pickle

我有一个 pickle 堆,是我从一个 friend 那里得到的,他让我像这样读它:

f = open('file.pickle')
import pickle
l = pickle.loads(f.read())

但是我得到一个 ImportErrorno module named sql.models

有人可以帮助我了解发生了什么吗?

最佳答案

您缺少重建 pickle 对象所需的代码。

Pickles 存储可以从中导入类的位置以及实例属性。仍然需要原始模块来重新创建模块。来自documentation :

Note that functions (built-in and user-defined) are pickled by “fully qualified” name reference, not by value. This means that only the function name is pickled, along with the name of the module the function is defined in. Neither the function’s code, nor any of its function attributes are pickled. Thus the defining module must be importable in the unpickling environment, and the module must contain the named object, otherwise an exception will be raised. [4]

Similarly, classes are pickled by named reference, so the same restrictions in the unpickling environment apply. Note that none of the class’s code or data is pickled, so in the following example the class attribute attr is not restored in the unpickling environment:

class Foo:
    attr = 'a class attr'

picklestring = pickle.dumps(Foo)

These restrictions are why picklable functions and classes must be defined in the top level of a module.

换句话说,用于创建 pickle 的原始数据至少包括一个自定义类的实例,该实例源自名为 sql.models 的模块。 .

一定要小心阅读随意的 pickle ,即使是来自 friend 的。 pickle 只是一种重新创建任意 Python 结构的堆栈语言。只要有足够的决心和技巧,您就可以构建一个 pickle,在您的计算机上生成一个 secret 的后门服务器。 pickle文档明确警告您:

Warning: The pickle module is not intended to be secure against erroneous or maliciously constructed data. Never unpickle data received from an untrusted or unauthenticated source.

这有 been a problem in the past ,即使对于经验丰富的开发人员也是如此。

关于 python : How to read pickle dump?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16045864/

相关文章:

python - 如何在 Python 中 pickle 复杂的枚举值

python - 为什么 gensim doc2vec 中的单词或文档向量之间几乎所有余弦相似度都是正的?

python - 从 Dash 下载包含多个工作表的 Excel 文件 (send_file)

c# - 通过代码从 .net 备份 Oracle 数据库

php - 如何只显示特定页数而不是所有页数?

python - 我无法将 ML 模型加载到尝试使用 joblib 和 pickle 的 flask 中

python - 创建新顶层时关闭现有顶层。 Tkinter Python 3

python - 如何计算一个实体与另一个实体一起出现的次数

mysql将结果限制为每行的第一个短语

python - 如何以python方式检查长时间运行的函数?