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

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
shelve
shelve、python shelve、shelve changes、python shelve模块、git shelve,以便于您获取更多的相关知识。

时间: 2024-08-03 12:04:07

shelve 用来持久化任意的Python对象实例代码_python的相关文章

Python群发邮件实例代码_python

直接上代码了 复制代码 代码如下: import smtplibmsg = MIMEMultipart() #构造附件1att1 = MIMEText(open('/home/a2bgeek/develop/python/hello.py', 'rb').read(), 'base64', 'gb2312')att1["Content-Type"] = 'application/octet-stream'att1["Content-Disposition"] = '

python 队列详解及实例代码_python

队列特性:先进先出(FIFO)--先进队列的元素先出队列.来源于我们生活中的队列(先排队的先办完事). Queue模块最常与threading模块一起构成生产-消费者模型,提供了一个适用于多线程编程的先进先出的数据结构,即队列. 该模块源码中包含5个类: 其中,Empty和Full是两个异常类,当队列的Queue.get(block=0)或者调用get_nowait()时,如果队列为空,则抛EmptyException异常. 同理,当队列的Queue.put(block=0)或者调用put_no

基于Python实现的扫雷游戏实例代码_python

本文实例借鉴mvc模式,核心数据为model,维护1个矩阵,0表无雷,1表雷,-1表已经检测过. 本例使用python的tkinter做gui,由于没考虑可用性问题,因此UI比较难看,pygame更有趣更强大更好看,做这些小游戏更合适,感兴趣的读者可以尝试一下! 具体的功能代码如下: # -*- coding: utf-8 -*- import random import sys from Tkinter import * class Model: """ 核心数据类,维护一

浅谈Python 对象内存占用_python

一切皆是对象 在 Python 一切皆是对象,包括所有类型的常量与变量,整型,布尔型,甚至函数. 参见stackoverflow上的一个问题 Is everything an object in python like ruby 代码中即可以验证: # everythin in python is object def fuction(): return print isinstance(True, object) print isinstance(0, object) print isinst

Python对象体系深入分析_python

本文较为详细的分析了了Python的对象体系.分享给大家供大家参考.具体如下: Guido用C语言创造了Python,在Python的世界中一切皆为对象. 一.C视角中的Python对象 让我们一起追溯到源头,Python由C语言实现,且向外提供了C的API http://docs.python.org/c-api/index.html . 我们思考问题的时候,可能对于对象这种东西很容易理解,而计算机能理解的只有0,1序列这样的字节序列,从根本上讲,我们所说的计算机语言中的对象只是在内存中的一块

python 打印出所有的对象/模块的属性(实例代码)_python

实例如下: import sys def print_all(module_): modulelist = dir(module_) length = len(modulelist) for i in range(0,length,1): print getattr(module_,modulelist[i]) print_all(sys) 以上这篇python 打印出所有的对象/模块的属性(实例代码)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持. 以上是小编为您精心

python 解析XML python模块xml.dom解析xml实例代码_python

一 .python模块 xml.dom 解析XML的APIminidom.parse(filename)加载读取XML文件 doc.documentElement获取XML文档对象 node.getAttribute(AttributeName)获取XML节点属性值 node.getElementsByTagName(TagName)获取XML节点对象集合 node.childNodes #返回子节点列表. node.childNodes[index].nodeValue获取XML节点值 nod

Python多线程实例教程_python

本文以实例形式较为详细的讲解了Python的多线程,是Python程序设计中非常重要的知识点.分享给大家供大家参考之用.具体方法如下: 用过Python的人都会觉得Python的多线程很类似于Java的多线程机制,但是比JAVA的多线程更灵活.在早期的Python多线程实现中,采用了thread模块.例如:   from time import ctime,sleep from thread import start_new_thread def loop1(): print "enter lo

python 转换 Javascript %u 字符串为python unicode的代码_python

web采集的数据为 %u6B63%u5F0F%u4EBA%u5458,需要读取并转换为python对象,想了下不调用Javascript去eval,只能自己翻译了. 核心代码: import re import codecs pattern = re.compile('%u[0-9A-Z]{4}') n = codecs.open('d:\\new.txt', 'w', 'utf-8') with open('d:\\p', 'r') as f: for l in f: for i in pat