最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

shelve  用來持久化任意的Python對(duì)象實(shí)例代碼

 更新時(shí)間:2016年10月12日 09:10:26   作者:東西南北風(fēng)  
這篇文章主要介紹了shelve 用來持久化任意的Python對(duì)象實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下

shelve -- 用來持久化任意的Python對(duì)象

這幾天接觸了Python中的shelve這個(gè)module,感覺比pickle用起來更簡單一些,它也是一個(gè)用來持久化Python對(duì)象的簡單工具。當(dāng)我們寫程序的時(shí)候如果不想用關(guān)系數(shù)據(jù)庫那么重量級(jí)的東東去存儲(chǔ)數(shù)據(jù),不妨可以試試用shelve。shelf也是用key來訪問的,使用起來和字典類似。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()

如果想要再次訪問這個(gè)shelf,只需要再次shelve.open()就可以了,然后我們可以像使用字典一樣來使用這個(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)行寫操作。所以當(dāng)我們知道我們的應(yīng)用如果只進(jìn)行讀操作,我們可以讓shelve通過只讀方式打開DB:

import shelve

s = shelve.open('test_shelf.db', flag='r')
try:
  existing = s['key1']
finally:
  s.close()

print existing

當(dāng)我們的程序試圖去修改一個(gè)以只讀方式打開的DB時(shí),將會(huì)拋一個(gè)訪問錯(cuò)誤的異常。異常的具體類型取決于anydbm這個(gè)模塊在創(chuàng)建DB時(shí)所選用的DB。

寫回(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è)例子中,由于一開始我們使用了缺省參數(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)該在打開shelf的時(shí)候?qū)riteback設(shè)置為True。當(dāng)我們將writeback這個(gè)flag設(shè)置為True以后,shelf將會(huì)將所有從DB中讀取的對(duì)象存放到一個(gè)內(nèi)存緩存。當(dāng)我們close()打開的shelf的時(shí)候,緩存中所有的對(duì)象會(huì)被重新寫入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ì)象都寫入到DB,這也會(huì)帶來額外的等待時(shí)間。因?yàn)閟helve沒有辦法知道緩存中哪些對(duì)象修改了,哪些對(duì)象沒有修改,因此所有的對(duì)象都會(huì)被寫入。

 $ 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'}

最后再來個(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ì)本站的支持!

相關(guān)文章

  • 詳解python中字典的循環(huán)遍歷的兩種方式

    詳解python中字典的循環(huán)遍歷的兩種方式

    本篇文章主要介紹了python中字典的循環(huán)遍歷的兩種方式 ,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-02-02
  • web.py在模板中輸出美元符號(hào)的方法

    web.py在模板中輸出美元符號(hào)的方法

    這篇文章主要介紹了web.py在模板中輸出美元符號(hào)的方法,即在web.py的模板中輸出$符號(hào)的方法,需要的朋友可以參考下
    2014-08-08
  • Python使用Pycharm必備插件推薦(非常好用!)

    Python使用Pycharm必備插件推薦(非常好用!)

    首先我們要知道pycharm是一款非常強(qiáng)大的python集成開發(fā)環(huán)境,帶有一整套python開發(fā)工具,這篇文章主要給大家介紹了關(guān)于Python使用Pycharm必備插件推薦的相關(guān)資料,需要的朋友可以參考下
    2023-11-11
  • Python入門教程之Python的安裝下載配置

    Python入門教程之Python的安裝下載配置

    這篇文章主要介紹了Python入門教程之Python的安裝下載配置,Python是一門非常強(qiáng)大好用的語言,也有著易上手的特性,本文為入門教程,需要的朋友可以參考下
    2023-04-04
  • python?中的?module?和?package

    python?中的?module?和?package

    這篇文章主要介紹了?python?中的?module?和?package?,文章基于Python的相關(guān)資料展開對(duì)主題的詳細(xì)介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下
    2022-04-04
  • python實(shí)現(xiàn)網(wǎng)站微信登錄的示例代碼

    python實(shí)現(xiàn)網(wǎng)站微信登錄的示例代碼

    這篇文章主要介紹了python實(shí)現(xiàn)網(wǎng)站微信登錄的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-09-09
  • Python之csv文件從MySQL數(shù)據(jù)庫導(dǎo)入導(dǎo)出的方法

    Python之csv文件從MySQL數(shù)據(jù)庫導(dǎo)入導(dǎo)出的方法

    今天小編就為大家分享一篇Python之csv文件從MySQL數(shù)據(jù)庫導(dǎo)入導(dǎo)出的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-06-06
  • 詳解pandas安裝若干異常及解決方案總結(jié)

    詳解pandas安裝若干異常及解決方案總結(jié)

    這篇文章主要介紹了詳解pandas安裝若干異常及解決方案總結(jié),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2019-01-01
  • python使用yaml格式文件的方法

    python使用yaml格式文件的方法

    本文主要介紹了python使用yaml格式文件的方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-07-07
  • Python連接SQLite數(shù)據(jù)庫操作實(shí)戰(zhàn)指南從入門到精通

    Python連接SQLite數(shù)據(jù)庫操作實(shí)戰(zhàn)指南從入門到精通

    在Python中使用SQLite進(jìn)行數(shù)據(jù)庫操作時(shí),我們將深入研究SQLite數(shù)據(jù)庫的創(chuàng)建、表格管理、數(shù)據(jù)插入、查詢、更新和刪除等關(guān)鍵主題,幫助你全面了解如何使用SQLite進(jìn)行數(shù)據(jù)庫操作
    2023-11-11

最新評(píng)論

剑川县| 西和县| 都兰县| 阆中市| 高陵县| 依安县| 天门市| 武清区| 巢湖市| 松滋市| 大庆市| 金华市| 华宁县| 嘉鱼县| 龙川县| 昔阳县| 绵竹市| 吉安市| 六枝特区| 南郑县| 溆浦县| 高要市| 乐东| 天等县| 庆安县| 思茅市| 富裕县| 方山县| 龙江县| 民权县| 定西市| 南投市| 巨鹿县| 土默特右旗| 扎囊县| 萨嘎县| 白水县| 都昌县| 荥阳市| 莱阳市| 额尔古纳市|