11.4.shelve — Python 对象持久化¶

“shelf” 是一种持久化的类似字典的对象。 与 “dbm” 数据库的区别在于 shelf 中的值(不是键!)实际上可以为任意 Python 对象 — 即 pickle 模块能够处理的任何东西。 这包括大部分类实例、递归数据类型,以及包含大量共享子对象的对象。 键则为普通的字符串。

shelve.open(filename, flag='c', protocol=None, writeback=False)¶

Open a persistent dictionary. The filename specified is the base filename for

the underlying database. As a side-effect, an extension may be added to the

filename and more than one file may be created. By default, the underlying

database file is opened for reading and writing. The optional flag parameter

has the same interpretation as the flag parameter of anydbm.open().

By default, version 0 pickles are used to serialize values. The version of the

pickle protocol can be specified with the protocol parameter.

在 2.3 版更改:The protocol parameter was added.

由于 Python 语义的限制,shelf 无法确定一个可变的持久化字典条目在何时被修改。 默认情况下 只有 在被修改对象再赋值给 shelf 时才会写入该对象 (参见 示例)。 如果可选的 writeback 形参设为 True,则所有被访问的条目都将在内存中被缓存,并会在 sync() 和 close() 时被写入;这可以使得对持久化字典中可变条目的修改更方便,但是如果访问的条目很多,这会消耗大量内存作为缓存,并会使得关闭操作变得非常缓慢,因为所有被访问的条目都需要写回到字典(无法确定被访问的条目中哪个是可变的,也无法确定哪个被实际修改了)。

Like file objects, shelve objects should be closed explicitly to ensure

that the persistent data is flushed to disk.

警告

由于 shelve 模块需要 pickle 的支持,因此从不可靠的来源载入 shelf 是不安全的。 与 pickle 一样,载入 shelf 时可以执行任意代码。

Shelf objects support most of the methods supported by dictionaries. This

eases the transition from dictionary based scripts to those requiring

persistent storage.

Note, the Python 3 transition methods (viewkeys(),

viewvalues(), and viewitems()) are not supported.

额外支持的两个方法:

Shelf.sync()¶

如果 shelf 打开时将 writeback 设为 True 则写回缓存中的所有条目。 如果可行还会清空缓存并将持久化字典同步到磁盘。 此方法会在使用 close() 关闭 shelf 时自动被调用。

Shelf.close()¶

同步并关闭持久化 dict 对象。 对已关闭 shelf 的操作将失败并引发 ValueError。

参见

持久化字典方案,使用了广泛支持的存储格式并具有原生字典的速度。

11.4.1.限制¶

The choice of which database package will be used (such as dbm,

gdbm or bsddb) depends on which interface is available. Therefore

it is not safe to open the database directly using dbm. The database is

also (unfortunately) subject to the limitations of dbm, if it is used —

this means that (the pickled representation of) the objects stored in the

database should be fairly small, and in rare cases key collisions may cause the

database to refuse updates.

shelve 模块不支持对 shelve 对象的 并发 读/写访问。 (多个同时读取访问则是安全的。) 当一个程序打开一个 shelve 对象来写入时,不应再有其他程序同时打开它来读取或写入。 Unix 文件锁定可被用来解决此问题,但这在不同 Unix 版本上会存在差异,并且需要有关所用数据库实现的细节知识。

classshelve.Shelf(dict, protocol=None, writeback=False)¶

A subclass of UserDict.DictMixin which stores pickled values in the

dict object.

By default, version 0 pickles are used to serialize values. The version of the

pickle protocol can be specified with the protocol parameter. See the

pickle documentation for a discussion of the pickle protocols.

在 2.3 版更改:The protocol parameter was added.

如果 writeback 形参为 True,对象将为所有访问过的条目保留缓存并在同步和关闭时将它们写回到 dict。 这允许对可变的条目执行自然操作,但是会消耗更多内存并让同步和关闭花费更长时间。

classshelve.BsdDbShelf(dict, protocol=None, writeback=False)¶

A subclass of Shelf which exposes first(), next(),

previous(), last() and set_location() which are available in

the bsddb module but not in other database modules. The dict object

passed to the constructor must support those methods. This is generally

accomplished by calling one of bsddb.hashopen(), bsddb.btopen() or

bsddb.rnopen(). The optional protocol and writeback parameters have

the same interpretation as for the Shelf class.

classshelve.DbfilenameShelf(filename, flag='c', protocol=None, writeback=False)¶

A subclass of Shelf which accepts a filename instead of a dict-like

object. The underlying file will be opened using anydbm.open(). By

default, the file will be created and opened for both read and write. The

optional flag parameter has the same interpretation as for the open()

function. The optional protocol and writeback parameters have the same

interpretation as for the Shelf class.

11.4.2.示例¶

对接口的总结如下 (key 为字符串,data 为任意对象):

import shelve

d = shelve.open(filename) # open -- file may get suffix added by low-level

# library

d[key] = data # store data at key (overwrites old data if

# using an existing key)

data = d[key] # retrieve a COPY of data at key (raise KeyError if no

# such key)

del d[key] # delete data stored at key (raises KeyError

# if no such key)

flag = d.has_key(key) # true if the key exists

klist = d.keys() # a list of all existing keys (slow!)

# as d was opened WITHOUT writeback=True, beware:

d['xx'] = range(4) # this works as expected, but...

d['xx'].append(5) # *this doesn't!* -- d['xx'] is STILL range(4)!

# having opened d without writeback=True, you need to code carefully:

temp = d['xx'] # extracts the copy

temp.append(5) # mutates the copy

d['xx'] = temp # stores the copy right back, to persist it

# or, d=shelve.open(filename,writeback=True) would let you just code

# d['xx'].append(5) and have it work as expected, BUT it would also

# consume more memory and make the d.close() operation slower.

d.close() # close it

参见

Module anydbmGeneric interface to dbm-style databases.

Module bsddbBSD db database interface.

Module dbhashThin layer around the bsddb which provides an open()

function like the other database modules.

Standard Unix database interface.

Portable implementation of the dbm interface.

Module gdbmGNU database interface, based on the dbm interface.

shelve 所使用的对象序列化。

High-performance version of pickle.

python中shelf对象_11.4. shelve — Python 对象持久化 — Python 2.7.18 文档相关推荐

  1. python中superclass是什么_深度解析并实现python中的super(转载,好文)

    大神半个月的成绩,让我看的叹为观止,建议看原帖地址,会让你对Python的描述符有更强的认识. 原文链接:https://blog.csdn.net/zhangjg_blog/article/deta ...

  2. python中ifelifelse用在什么结构_详解Python if-elif-else知识点

    有的时候,一个 if - else - 还不够用.比如,根据年龄的划分:条件1:18岁或以上:adult 条件2:6岁或以上:teenager 条件3:6岁以下:kid Python if-elif- ...

  3. python字符串能减吗_在python中减去两个字符串(Subtract two strings in python)

    在python中减去两个字符串(Subtract two strings in python) 我应该计算两个不同列表的元素之间的差异. 这是我的代码: import operator a = ['5 ...

  4. python中的常量可以修改吗_深入理解Python变量与常量

    变量是计算机内存中的一块区域,变量可以存储规定范围内的值,而且值可以改变.基于变量的数据类型,解释器会分配指定内存,并决定什么数据可以被存储在内存中.常量是一块只读的内存区域,常量一旦被初始化就不能被 ...

  5. python中for无限循环_关于循环:在Python中从1循环到无穷大

    在C语言中,我会这样做: 1 2 3 4int i; for (i = 0;; i++) if (thereIsAReasonToBreak(i)) break; 如何在Python中实现类似的功能? ...

  6. Python实现谷歌翻译爬虫,翻译PDF,翻译Excel,支持excel文档打开翻译,支持xlsx,xlsm等格式。

    前言: 这两个Python脚本是我在实习期间完成的,具体来自于小组主管的两个小需求.做完之后感觉还是挺有收获的. 实现谷歌翻译,首先需要将我们写的Python脚本还有需要翻译的文件放到谷歌浏览器的安装 ...

  7. 计算机毕业设计Python+djang的小区疫情防控系统(源码+系统+mysql数据库+Lw文档)

    项目介绍 随着信息化时代的到来,管理系统都趋向于智能化.系统化,居民小区疫情防控管理系统也不例外,但目前国内的市场仍都使用人工管理,市场规模越来越大,同时信息量也越来越庞大,人工管理显然已无法应对时代 ...

  8. 计算机毕业设计Python+django大学生闲置二手交易商城平台(源码+系统+mysql数据库+Lw文档)

    项目介绍 当前在市场经济的快速发展下,我国的经济形势也在不断的发展壮大.特别是在计算机信息化的普及下,新的互联网+业态促使着零售业在不断的转型发展.随着B2C.O2O的不断发展,传统的零售实体都受到了 ...

  9. 计算机毕业设计Python+djang的图书馆图书借阅归还管理系统(源码+系统+mysql数据库+Lw文档)

    项目介绍 论文阐述了图书管理系统,并对该系统的需求分析及系统需要实现的设计方法作了介绍.该系统的基本功能包括读者登录,修改密码,读者管理,图书管理和借阅管理等功能,并且个个模块都包括了添加修改和删除和 ...

  10. 基于python食品安全溯源管理系统django框架计算机毕业设计源码+系统+数据库+lw文档+调试部署

    基于python食品安全溯源管理系统django框架计算机毕业设计源码+系统+数据库+lw文档+调试部署 基于python食品安全溯源管理系统django框架计算机毕业设计源码+系统+数据库+lw文档 ...

最新文章

  1. java sip 携带sdp_SIP中的SDP offer/answer交换初探
  2. selenium如何操作HTML5的画布canvas上的元素
  3. 解决 macOS 上 iterm2 使用 rz/sz 卡死的问题
  4. 基于intellij和meavn的整合开发struts2框架的web程序
  5. 内存管理(ybtoj-二叉堆)
  6. 电子数字计算机最早应用于哪个领域,2013计算机一级B考试模拟试题及答案(2)...
  7. BitAdminCore框架更新日志20180529
  8. html清除视频缓存,html清除页面缓存
  9. 如何避免ASP.NET网页初次加载缓慢
  10. Pycharm新建文件时头部模板的配置方法
  11. RoR介绍:一个Java程序员的开发体验
  12. 判断输入的字符与已知字符相等_你会输入带圈字符吗?
  13. java c语言 关系_java和c语言有什么共同点?
  14. ISP成像算法基础Day1—Python基础
  15. Win10更新后网络图标变成了英文怎么办?
  16. 北航计算机组成实验课,北航计算机组成实验Project4
  17. 功能测试用例需要详细到什么程度,完全测试程序是可能的么
  18. 2021年南京大学842考研-软件工程部分代码设计题
  19. CET-6--2018.12--1
  20. 别忽略国美之争的真正遗产

热门文章

  1. nyoj1016德莱联盟【判断两线段是否相交】
  2. PHP WEB程序设计信息表,WEB程序设计(PHP)2020知到答案全套
  3. infoq_InfoQ与Azul Systems Gil Tene谈论Zing,Zulu和新版本
  4. Qt(一)消息提示框
  5. 第十二届蓝桥杯大赛软件赛省赛 Java 大学 B 组(2021年4月18日)
  6. 心流_追求生命的意义
  7. 【亲测好用】一站式视频录制编辑软件:Filmage Screen mac中文版
  8. web多媒体技术在视频编辑场景的应用
  9. Criterion和Criteria
  10. C语言—打印1000年到2000年的闰年