shelve  用来持久化任意的Python对象实例代码


Posted in Python onOctober 12, 2016

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()

感谢阅读本文,希望能帮助到大家,谢谢大家对本站的支持!

Python 相关文章推荐
python编写暴力破解FTP密码小工具
Nov 19 Python
Windows下用py2exe将Python程序打包成exe程序的教程
Apr 08 Python
深入解读Python解析XML的几种方式
Feb 16 Python
Python多进程同步简单实现代码
Apr 27 Python
浅谈Python的垃圾回收机制
Dec 17 Python
matplotlib 输出保存指定尺寸的图片方法
May 24 Python
Pyqt QImage 与 np array 转换方法
Jun 27 Python
pycharm 批量修改变量名称的方法
Aug 01 Python
Python2 与Python3的版本区别实例分析
Mar 30 Python
python 基于selenium实现鼠标拖拽功能
Dec 24 Python
Python爬虫+tkinter界面实现历史天气查询的思路详解
Feb 22 Python
浅谈Python数学建模之固定费用问题
Jun 23 Python
Pyhton中单行和多行注释的使用方法及规范
Oct 11 #Python
使用Python脚本实现批量网站存活检测遇到问题及解决方法
Oct 11 #Python
深入浅析ImageMagick命令执行漏洞
Oct 11 #Python
Zabbix实现微信报警功能
Oct 09 #Python
python 2.6.6升级到python 2.7.x版本的方法
Oct 09 #Python
Django1.7+python 2.78+pycharm配置mysql数据库
Oct 09 #Python
解决python2.7 查询mysql时出现中文乱码
Oct 09 #Python
You might like
php数组函数序列之array_combine() - 数组合并函数使用说明
2011/10/29 PHP
PHP简单获取视频预览图的方法
2015/03/12 PHP
yii2.0数据库迁移教程【多个数据库同时同步数据】
2016/10/08 PHP
PHP连接及操作PostgreSQL数据库的方法详解
2019/01/30 PHP
smarty模板的使用方法实例分析
2019/09/18 PHP
js 页面执行时间计算代码
2009/03/04 Javascript
Jquery实现图片放大镜效果的思路及代码(自写)
2013/10/18 Javascript
instanceof和typeof运算符的区别详解
2014/01/06 Javascript
抛弃Nginx使用nodejs做反向代理服务器
2014/07/17 NodeJs
JavaScript驾驭网页-CSS与DOM
2016/03/24 Javascript
vue.js实现点击后动态添加class及删除同级class的实现代码
2018/04/04 Javascript
JS使用tween.js动画库实现轮播图并且有切换功能
2018/07/17 Javascript
基于AngularJs select绑定数字类型的问题
2018/10/08 Javascript
javascript实现打砖块小游戏(附完整源码)
2020/09/18 Javascript
jquery实现图片放大镜效果
2020/12/23 jQuery
Python 过滤字符串的技巧,map与itertools.imap
2008/09/06 Python
Python的Bottle框架中实现最基本的get和post的方法的教程
2015/04/30 Python
python通过imaplib模块读取gmail里邮件的方法
2015/05/08 Python
Flask框架中密码的加盐哈希加密和验证功能的用法详解
2016/06/07 Python
基于Python数据可视化利器Matplotlib,绘图入门篇,Pyplot详解
2017/10/13 Python
Python实现批量修改图片格式和大小的方法【opencv库与PIL库】
2018/12/03 Python
Python获取Redis所有Key以及内容的方法
2019/02/19 Python
Python3网络爬虫中的requests高级用法详解
2019/06/18 Python
python 魔法函数实例及解析
2019/09/25 Python
用python介绍4种常用的单链表翻转的方法小结
2020/02/24 Python
TensorFlow的环境配置与安装教程详解(win10+GeForce GTX1060+CUDA 9.0+cuDNN7.3+tensorflow-gpu 1.12.0+python3.5.5)
2020/06/22 Python
Python+OpenCV检测灯光亮点的实现方法
2020/11/02 Python
Python实现哲学家就餐问题实例代码
2020/11/09 Python
python的setattr函数实例用法
2020/12/16 Python
Yahoo的PHP面试题
2014/05/26 面试题
副科级后备干部考察材料
2014/05/15 职场文书
图书馆标语
2014/06/19 职场文书
职业道德模范事迹材料
2014/08/24 职场文书
2014年仓库管理工作总结
2014/12/17 职场文书
仓库管理员岗位职责
2015/02/03 职场文书
小鞋子观后感
2015/06/05 职场文书