shelve 用來持久化任意的Python對象執行個體代碼

來源:互聯網
上載者:User
shelve -- 用來持久化任意的Python對象

這幾天接觸了Python中的shelve這個module,感覺比pickle用起來更簡單一些,它也是一個用來持久化Python對象的簡單工具。當我們寫程式的時候如果不想用關聯式資料庫那麼重量級的東東去儲存資料,不妨可以試試用shelve。shelf也是用key來訪問的,使用起來和字典類似。shelve其實用anydbm去建立DB並且管理持久化對象的。

建立一個新的shelf

直接使用shelve.open()就可以建立了

import shelves = shelve.open('test_shelf.db')try:  s['key1'] = { 'int': 10, 'float':9.5, 'string':'Sample data' }finally:  s.close()

如果想要再次訪問這個shelf,只需要再次shelve.open()就可以了,然後我們可以像使用字典一樣來使用這個shelf

import shelves = 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 shelves = 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 shelves = 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 shelves = 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 pythonimport timeimport datetimeimport md5import shelveLOGIN_TIME_OUT = 60db = 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 '-->', dbdef 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)uitEnter 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()

感謝閱讀本文,希望能協助到大家,謝謝大家對本站的支援!

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.