shelve模塊是一個簡單的k,v將內存數據經過文件持久化的模塊,能夠持久化任何pickle可支持的python數據格式html
建立一個新的shelfpython
直接使用shelve.open()就能夠建立了
複製代碼web
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,咱們將獲得以下輸出:ruby
$ python shelve_create.py
$ python shelve_existing.py
{'int': 10, 'float': 9.5, 'string': 'Sample data'}
dbm這個模塊有個限制,它不支持多個應用同一時間往同一個DB進行寫操做。因此當咱們知道咱們的應用若是隻進行讀操做,咱們可讓shelve經過只讀方式打開DB:svg
import shelve
s = shelve.open('test_shelf.db', flag='r')
try:
existing = s['key1']
finally:
s.close()
print existing
當咱們的程序試圖去修改一個以只讀方式打開的DB時,將會拋一個訪問錯誤的異常。異常的具體類型取決於anydbm這個模塊在建立DB時所選用的DB。ui
寫回(Write-back)this
因爲shelve在默認狀況下是不會記錄待持久化對象的任何修改的,因此咱們在shelve.open()時候須要修改默認參數,不然對象的修改不會保存。
複製代碼spa
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()也不會被保存。code
執行結果以下:
$ 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()
轉自:https://www.cnblogs.com/frankzs/p/5949645.html