shelve 用來(lái)持久化任意的Python對(duì)象實(shí)例代碼
shelve -- 用來(lái)持久化任意的Python對(duì)象
這幾天接觸了Python中的shelve這個(gè)module,感覺(jué)比pickle用起來(lái)更簡(jiǎn)單一些,它也是一個(gè)用來(lái)持久化Python對(duì)象的簡(jiǎn)單工具。當(dāng)我們寫(xiě)程序的時(shí)候如果不想用關(guān)系數(shù)據(jù)庫(kù)那么重量級(jí)的東東去存儲(chǔ)數(shù)據(jù),不妨可以試試用shelve。shelf也是用key來(lái)訪問(wèn)的,使用起來(lái)和字典類似。shelve其實(shí)用anydbm去創(chuàng)建DB并且管理持久化對(duì)象的。
創(chuàng)建一個(gè)新的shelf
直接使用shelve.open()就可以創(chuàng)建了
import shelve s = shelve.open('test_shelf.db') try: s['key1'] = { 'int': 10, 'float':9.5, 'string':'Sample data' } finally: s.close()
如果想要再次訪問(wèn)這個(gè)shelf,只需要再次shelve.open()就可以了,然后我們可以像使用字典一樣來(lái)使用這個(gè)shelf
import shelve s = shelve.open('test_shelf.db') try: existing = s['key1'] finally: s.close() print existing
當(dāng)我們運(yùn)行以上兩個(gè)py,我們將得到如下輸出:
$ python shelve_create.py $ python shelve_existing.py {'int': 10, 'float': 9.5, 'string': 'Sample data'}
dbm這個(gè)模塊有個(gè)限制,它不支持多個(gè)應(yīng)用同一時(shí)間往同一個(gè)DB進(jìn)行寫(xiě)操作。所以當(dāng)我們知道我們的應(yīng)用如果只進(jìn)行讀操作,我們可以讓shelve通過(guò)只讀方式打開(kāi)DB:
import shelve s = shelve.open('test_shelf.db', flag='r') try: existing = s['key1'] finally: s.close() print existing
當(dāng)我們的程序試圖去修改一個(gè)以只讀方式打開(kāi)的DB時(shí),將會(huì)拋一個(gè)訪問(wèn)錯(cuò)誤的異常。異常的具體類型取決于anydbm這個(gè)模塊在創(chuàng)建DB時(shí)所選用的DB。
寫(xiě)回(Write-back)
由于shelve在默認(rèn)情況下是不會(huì)記錄待持久化對(duì)象的任何修改的,所以我們?cè)趕helve.open()時(shí)候需要修改默認(rèn)參數(shù),否則對(duì)象的修改不會(huì)保存。
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()
上面這個(gè)例子中,由于一開(kāi)始我們使用了缺省參數(shù)shelve.open()了,因此第6行修改的值即使我們s.close()也不會(huì)被保存。
執(zhí)行結(jié)果如下:
$ python shelve_create.py $ python shelve_withoutwriteback.py {'int': 10, 'float': 9.5, 'string': 'Sample data'} {'int': 10, 'float': 9.5, 'string': 'Sample data'}
所以當(dāng)我們?cè)噲D讓shelve去自動(dòng)捕獲對(duì)象的變化,我們應(yīng)該在打開(kāi)shelf的時(shí)候?qū)riteback設(shè)置為True。當(dāng)我們將writeback這個(gè)flag設(shè)置為True以后,shelf將會(huì)將所有從DB中讀取的對(duì)象存放到一個(gè)內(nèi)存緩存。當(dāng)我們close()打開(kāi)的shelf的時(shí)候,緩存中所有的對(duì)象會(huì)被重新寫(xiě)入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方式有優(yōu)點(diǎn)也有缺點(diǎn)。優(yōu)點(diǎn)是減少了我們出錯(cuò)的概率,并且讓對(duì)象的持久化對(duì)用戶更加的透明了;但這種方式并不是所有的情況下都需要,首先,使用writeback以后,shelf在open()的時(shí)候會(huì)增加額外的內(nèi)存消耗,并且當(dāng)DB在close()的時(shí)候會(huì)將緩存中的每一個(gè)對(duì)象都寫(xiě)入到DB,這也會(huì)帶來(lái)額外的等待時(shí)間。因?yàn)閟helve沒(méi)有辦法知道緩存中哪些對(duì)象修改了,哪些對(duì)象沒(méi)有修改,因此所有的對(duì)象都會(huì)被寫(xiě)入。
$ 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'}
最后再來(lái)個(gè)復(fù)雜一點(diǎn)的例子:
#!/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()
感謝閱讀本文,希望能幫助到大家,謝謝大家對(duì)本站的支持!
- python序列化與數(shù)據(jù)持久化實(shí)例詳解
- Python數(shù)據(jù)持久化shelve模塊用法分析
- Python中的數(shù)據(jù)對(duì)象持久化存儲(chǔ)模塊pickle的使用示例
- 詳解python持久化文件讀寫(xiě)
- 將Python中的數(shù)據(jù)存儲(chǔ)到系統(tǒng)本地的簡(jiǎn)單方法
- Python通過(guò)調(diào)用mysql存儲(chǔ)過(guò)程實(shí)現(xiàn)更新數(shù)據(jù)功能示例
- Python3爬蟲(chóng)學(xué)習(xí)之MySQL數(shù)據(jù)庫(kù)存儲(chǔ)爬取的信息詳解
- python將類似json的數(shù)據(jù)存儲(chǔ)到MySQL中的實(shí)例
- python3爬蟲(chóng)學(xué)習(xí)之?dāng)?shù)據(jù)存儲(chǔ)txt的案例詳解
- Python編寫(xiě)通訊錄通過(guò)數(shù)據(jù)庫(kù)存儲(chǔ)實(shí)現(xiàn)模糊查詢功能
- Python數(shù)據(jù)持久化存儲(chǔ)實(shí)現(xiàn)方法分析
相關(guān)文章
python中的turtle庫(kù)函數(shù)簡(jiǎn)單使用教程
這篇文章主要介紹了python中的turtle庫(kù)函數(shù)簡(jiǎn)單使用教程。本文通過(guò)圖片的形式給大家展示的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2018-07-07Jupyter notebook運(yùn)行Spark+Scala教程
這篇文章主要介紹了Jupyter notebook運(yùn)行Spark+Scala教程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-04-04PyQt5每天必學(xué)之日歷控件QCalendarWidget
這篇文章主要為大家詳細(xì)介紹了PyQt5每天必學(xué)之日歷控件QCalendarWidget,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-04-04python二分法查找算法實(shí)現(xiàn)方法【遞歸與非遞歸】
這篇文章主要介紹了python二分法查找算法實(shí)現(xiàn)方法,結(jié)合實(shí)例形式分析了Python使用遞歸與非遞歸算法實(shí)現(xiàn)二分查找的相關(guān)操作技巧,需要的朋友可以參考下2019-12-12python密碼學(xué)簡(jiǎn)單替代密碼解密及測(cè)試教程
這篇文章主要介紹了python密碼學(xué)簡(jiǎn)單替代密碼解密及測(cè)試教程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05Python中read,readline和readlines的區(qū)別案例詳解
這篇文章主要介紹了Python中read,readline和readlines的區(qū)別案例詳解,本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-09-09