gpt4 book ai didi

python - 如何用Python保存数据?

转载 作者:太空狗 更新时间:2023-10-29 17:12:09 25 4
gpt4 key购买 nike

我正在用 Python 开发一个程序,希望用户能够保存他们正在处理的数据。我调查了 cPickle;这似乎是一种快速简便的数据保存方式,但似乎不安全。由于可以 pickle 整个函数、类等,我担心流氓保存文件可能会向程序中注入(inject)有害代码。有什么方法可以防止这种情况发生,或者我是否应该研究其他保存数据的方法,例如直接转换为字符串(这似乎也不安全)或创建 XML 层次结构,然后将数据放入其中。

我是 python 的新手,所以请多多包涵。

提前致谢!

编辑:至于我存储的数据类型,主要是字典和列表。名称、速度等信息。目前还比较简单,但将来可能会变得更复杂。

最佳答案

根据您的描述,JSON 编码是安全且快速的解决方案。 python2.6中有一个json模块,你可以这样使用:

import json
obj = {'key1': 'value1', 'key2': [1, 2, 3, 4], 'key3': 1322}
encoded = json.dumps(obj)
obj = json.loads(encoded)

JSON 格式是人类可读的,非常类似于 python 中的字典字符串表示。并且没有像 pickle 这样的任何安全问题。如果你没有 python2.6 你可以安装 cjson 或 simplejson

你不能像 Pickle 一样使用 JSON 来保存 python 对象。但是您可以使用它来保存:字符串、字典、列表……对于大多数情况来说这已经足够了。

解释为什么 pickle 不安全。 来自 python docs :

Most of the security issues surrounding the pickle and cPickle module involve unpickling. There are no known security vulnerabilities related to pickling because you (the programmer) control the objects that pickle will interact with, and all it produces is a string.

However, for unpickling, it is never a good idea to unpickle an untrusted string whose origins are dubious, for example, strings read from a socket. This is because unpickling can create unexpected objects and even potentially run methods of those objects, such as their class constructor or destructor ... The moral of the story is that you should be really careful about the source of the strings your application unpickles.

有一些方法可以保护你自己,但在你的情况下使用 JSON 更容易。

关于python - 如何用Python保存数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1389738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com