shelve -- 用来持久化任意的Python对象
这几天接触了Python中的shelve这个module,感觉比pickle用起来更简单一些,它也是一个用来持久化Python对象的简单工具。当我们写程序的时候如果不想用关系数据库那么重量级的东东去存储数据,不妨可以试试用shelve。shelf也是用key来访问的,使用起来和字典类似。shelve其实用anydbm去创建DB并且管理持久化对象的。
创建一个新的shelf
直接使用shelve.open()就可以创建了
- import shelve
- s = shelve.open('test_shelf.db')
- try:
- s['key1'] = { 'int': 10, 'float':9.5, 'string':'Sample data' }
- finally:
- s.close()
如果想要再次访问这个shelf,只需要再次shelve.open()就可以了,然后我们可以像使用字典一样来使用这个shelf
- import shelve
- s = shelve.open('test_shelf.db')
- try:
- existing = s['key1']
- finally:
- s.close()
- print existing
当我们运行以上两个py,我们将得到如下输出:
- $ python shelve_create.py
- $ python shelve_existing.py
- {'int': 10, 'float': 9.5, 'string': 'Sample data'}
dbm这个模块有个限制,它不支持多个应用同一时间往同一个DB进行写操作。所以当我们知道我们的应用如果只进行读操作,我们可以让shelve通过只读方式打开DB:
- import shelve
- s = shelve.open('test_shelf.db', flag='r')
- try:
- existing = s['key1']
- finally:
- s.close()
- print existing
当我们的程序试图去修改一个以只读方式打开的DB时,将会抛一个访问错误的异常。异常的具体类型取决于anydbm这个模块在创建DB时所选用的DB。
写回(Write-back)
由于shelve在默认情况下是不会记录待持久化对象的任何修改的,所以我们在shelve.open()时候需要修改默认参数,否则对象的修改不会保存。
- import shelve
- s = shelve.open('test_shelf.db')
- try:
- print s['key1']
- s['key1']['new_value'] = 'this was not here before'
- finally:
- s.close()
- s = shelve.open('test_shelf.db', writeback=True)
- try:
- print s['key1']
- finally:
- s.close()
上面这个例子中,由于一开始我们使用了缺省参数shelve.open()了,因此第6行修改的值即使我们s.close()也不会被保存。
执行结果如下:
- $ python shelve_create.py
- $ python shelve_withoutwriteback.py
- {'int': 10, 'float': 9.5, 'string': 'Sample data'}
- {'int': 10, 'float': 9.5, 'string': 'Sample data'}
所以当我们试图让shelve去自动捕获对象的变化,我们应该在打开shelf的时候将writeback设置为True。当我们将writeback这个flag设置为True以后,shelf将会将所有从DB中读取的对象存放到一个内存缓存。当我们close()打开的shelf的时候,缓存中所有的对象会被重新写入DB。
- import shelve
- s = shelve.open('test_shelf.db', writeback=True)
- try:
- print s['key1']
- s['key1']['new_value'] = 'this was not here before'
- print s['key1']
- finally:
- s.close()
- s = shelve.open('test_shelf.db', writeback=True)
- try:
- print s['key1']
- finally:
- s.close()
writeback方式有优点也有缺点。优点是减少了我们出错的概率,并且让对象的持久化对用户更加的透明了;但这种方式并不是所有的情况下都需要,首先,使用writeback以后,shelf在open()的时候会增加额外的内存消耗,并且当DB在close()的时候会将缓存中的每一个对象都写入到DB,这也会带来额外的等待时间。因为shelve没有办法知道缓存中哪些对象修改了,哪些对象没有修改,因此所有的对象都会被写入。
- $ python shelve_create.py
- $ python shelve_writeback.py
- {'int': 10, 'float': 9.5, 'string': 'Sample data'}
- {'int': 10, 'new_value': 'this was not here before', 'float': 9.5, 'string': 'Sample data'}
- {'int': 10, 'new_value': 'this was not here before', 'float': 9.5, 'string': 'Sample data'}
最后再来个复杂一点的例子:
- #!/bin/env python
- import time
- import datetime
- import md5
- import shelve
- LOGIN_TIME_OUT = 60
- db = shelve.open('user_shelve.db', writeback=True)
- def newuser():
- global db
- prompt = "login desired: "
- while True:
- name = raw_input(prompt)
- if name in db:
- prompt = "name taken, try another: "
- continue
- elif len(name) == 0:
- prompt = "name should not be empty, try another: "
- continue
- else:
- break
- pwd = raw_input("password: ")
- db[name] = {"password": md5_digest(pwd), "last_login_time": time.time()}
- #print '-->', db
- def olduser():
- global db
- name = raw_input("login: ")
- pwd = raw_input("password: ")
- try:
- password = db.get(name).get('password')
- except AttributeError, e:
- print "\033[1;31;40mUsername '%s' doesn't existed\033[0m" % name
- return
- if md5_digest(pwd) == password:
- login_time = time.time()
- last_login_time = db.get(name).get('last_login_time')
- if login_time - last_login_time < LOGIN_TIME_OUT:
- print "\033[1;31;40mYou already logged in at: <%s>\033[0m" % datetime.datetime.fromtimestamp(last_login_time).isoformat()
- db[name]['last_login_time'] = login_time
- print "\033[1;32;40mwelcome back\033[0m", name
- else:
- print "\033[1;31;40mlogin incorrect\033[0m"
- def md5_digest(plain_pass):
- return md5.new(plain_pass).hexdigest()
- def showmenu():
- #print '>>>', db
- global db
- prompt = """
- (N)ew User Login
- (E)xisting User Login
- (Q)uit
- Enter choice: """
- done = False
- while not done:
- chosen = False
- while not chosen:
- try:
- choice = raw_input(prompt).strip()[0].lower()
- except (EOFError, KeyboardInterrupt):
- choice = "q"
- print "\nYou picked: [%s]" % choice
- if choice not in "neq":
- print "invalid option, try again"
- else:
- chosen = True
- if choice == "q": done = True
- if choice == "n": newuser()
- if choice == "e": olduser()
- db.close()
- if __name__ == "__main__":
- showmenu()
shelve -- 用来持久化任意的Python对象的更多相关文章
- pickle和cPickle:Python对象的序列化(上)
https://segmentfault.com/a/1190000002493548 pickle模块实现了一种算法,将任意一个Python对象转化成一系列字节(byets).此过程也调用了seri ...
- python对象序列化或持久化的方法
http://blog.csdn.net/chen_lovelotus/article/details/7233293 一.Python对象持久化方法 目前为止,据我所知,在python中对象持久化有 ...
- 【Python】 python对象的文件化 pickle
pickle 之前隐隐约约在哪里看到过pickle这个模块但一直没怎么用过.然后让我下定决心学习一下这个模块的原因竟然是[妹抖龙女(男)主在工作中用到了pickle哈哈哈].嗯嗯,不扯皮了.pickl ...
- 十:python 对象类型详解六:文件
一:文件 1.简介:内置open 函数会创建一个python 文件对象,可以作为计算机上的一个文件链接.在调用open 之后,可以通过调用返回文件对象的方法来读写相关外部文件.文件对象只是常见文件处理 ...
- Python 对象(type/object/class) 作用域 一等函数 (慕课--Python高级,IO并发 第二章)
在python中一共有两种作用域:全局作用域和函数作用域全局作用域:在全局都有效,全局作用域在程序执行时创建,在程序执行结束时销毁:所有函数以外的区域都是全局作用域:在全局作用域中定义的变量,都属于全 ...
- 如何将Python对象保存在本地文件中?
Python对象的永久存储 1.使用Python的pickle模块 import pickle class A: def __init__(self,name,a): self.name=name s ...
- Python对象的循环引用问题
目录 Python对象循环引用 循环引用垃圾回收算法 容器对象 生成容器对象 追踪容器对象 结束追踪容器对象 分代容器对象链表 何时执行循环引用垃圾回收 循环引用的垃圾回收 循环引用中的终结器 pyt ...
- 《python解释器源码剖析》第1章--python对象初探
1.0 序 对象是python中最核心的一个概念,在python的世界中,一切都是对象,整数.字符串.甚至类型.整数类型.字符串类型,都是对象.换句话说,python中面向对象的理念观测的非常彻底,面 ...
- cPickle对python对象进行序列化,序列化到文件或内存
pickle模块使用的数据格式是python专用的,并且不同版本不向后兼容,同时也不能被其他语言说识别.要和其他语言交互,可以使用内置的json包 cPickle可以对任意一种类型的python对象进 ...
随机推荐
- SpringCloud开发学习总结(七)—— 声明式服务调用Feign(三)
Feign中的Ribbon配置 由于Spring Cloud Feign的客户端负载均衡是通过Spring Cloud Ribbon实现的,所以我们可以直接通过配置Ribbon客户端的方式来自定义各个 ...
- Apache Kylin Cube 的存储
不多说,直接上干货! 简单的说Cuboid的维度会映射为HBase的Rowkey,Cuboid的指标会映射为HBase的Value. Cube映射成HBase存储 如上图原始表所示:Hive表有两个维 ...
- Design Patterns Uncovered: The Chain Of Responsibility Pattern
Chain of Responsibility in the Real World The idea of the Chain Of Responsibility is that it avoids ...
- [转]Android 完美退出 App (Exit)
本文转自:http://blog.csdn.net/zeus_9i/article/details/7259881 最近两天为了解决Android上面退出程序问题折腾了半死,在google & ...
- Spring Cloud Config 使用Bus的动态配置中心
server端配置 POM文件 <dependency> <groupId>org.springframework.boot</groupId> <artif ...
- Intent实现界面跳转、程序跳转
一个程序往往由多个界面组成,界面之间的跳转,实质是Activity之间的跳转. 从当前程序跳转到其它程序,实质是启动了目标程序的入口Activity. Intent被称为意图,常用于组件之间的交互,可 ...
- 微信小程序 图片加载失败处理方案
小程序端展示网络资源图片可能会失败,下面介绍一种自己的处理方法 1. js文件中判断图片 url 是否存在,存在则正常显示,不存在则替换url为本地默认图片 2. 当图片 url 存在,但是加载失败时 ...
- 【学习笔记】深入理解js原型和闭包(9)—— 简述【执行上下文】下
继续上一篇文章(https://www.cnblogs.com/lauzhishuai/p/10078231.html)的内容. 上一篇我们讲到在全局环境下的代码段中,执行上下文环境中有如何数据: 变 ...
- How exception works ?
这是2013年写的一篇旧文,放在gegahost.net上面 http://raison.gegahost.net/?p=28 February 18, 2013 How exception work ...
- [python3]PyCharm编辑器
简介 Python有丰富的开发工具,本教程不一一进行介绍,只推荐大家使用PyCharm,因为python开发者都在用它,但缺点就是消耗电脑资源,如果你电脑配置低,就会比较卡 下载 下载地址: http ...