99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線(xiàn)電話(huà):13121318867

登錄
首頁(yè)精彩閱讀舉例簡(jiǎn)單講解Python中的數(shù)據(jù)存儲(chǔ)模塊shelve的用法
舉例簡(jiǎn)單講解Python中的數(shù)據(jù)存儲(chǔ)模塊shelve的用法
2017-11-03
收藏

舉例簡(jiǎn)單講解Python中的數(shù)據(jù)存儲(chǔ)模塊shelve的用法

shelve類(lèi)似于一個(gè)key-value數(shù)據(jù)庫(kù),可以很方便的用來(lái)保存Python的內(nèi)存對(duì)象,其內(nèi)部使用pickle來(lái)序列化數(shù)據(jù),簡(jiǎn)單來(lái)說(shuō),使用者可以將一個(gè)列表、字典、或者用戶(hù)自定義的類(lèi)實(shí)例保存到shelve中,下次需要用的時(shí)候直接取出來(lái),就是一個(gè)Python內(nèi)存對(duì)象,不需要像傳統(tǒng)數(shù)據(jù)庫(kù)一樣,先取出數(shù)據(jù),然后用這些數(shù)據(jù)重新構(gòu)造一遍所需要的對(duì)象。下面是簡(jiǎn)單示例:

import shelve

def test_shelve():
  # open 返回一個(gè)Shelf類(lèi)的實(shí)例
  #
  # 參數(shù)flag的取值范圍:
  # 'r':只讀打開(kāi)
  # 'w':讀寫(xiě)訪問(wèn)
  # 'c':讀寫(xiě)訪問(wèn),如果不存在則創(chuàng)建
  # 'n':讀寫(xiě)訪問(wèn),總是創(chuàng)建新的、空的數(shù)據(jù)庫(kù)文件
  #
  # protocol:與pickle庫(kù)一致
  # writeback:為T(mén)rue時(shí),當(dāng)數(shù)據(jù)發(fā)生變化會(huì)回寫(xiě),不過(guò)會(huì)導(dǎo)致內(nèi)存開(kāi)銷(xiāo)比較大
  d = shelve.open('shelve.db', flag='c', protocol=2, writeback=False)
  assert isinstance(d, shelve.Shelf)
 
  # 在數(shù)據(jù)庫(kù)中插入一條記錄
  d['abc'] = {'name': ['a', 'b']}
  d.sync()
 
  print d['abc']
 
  # writeback是False,因此對(duì)value進(jìn)行修改是不起作用的
  d['abc']['x'] = 'x'
  print d['abc'] # 還是打印 {'name': ['a', 'b']}
 
  # 當(dāng)然,直接替換key的value還是起作用的
  d['abc'] = 'xxx'
  print d['abc']
 
  # 還原abc的內(nèi)容,為下面的測(cè)試代碼做準(zhǔn)備
  d['abc'] = {'name': ['a', 'b']}
  d.close()
 
  # writeback 為 True 時(shí),對(duì)字段內(nèi)容的修改會(huì)writeback到數(shù)據(jù)庫(kù)中。
  d = shelve.open('shelve.db', writeback=True)
 
  # 上面我們已經(jīng)保存了abc的內(nèi)容為{'name': ['a', 'b']},打印一下看看對(duì)不對(duì)
  print d['abc']
 
  # 修改abc的value的部分內(nèi)容
  d['abc']['xx'] = 'xxx'
  print d['abc']
  d.close()
 
  # 重新打開(kāi)數(shù)據(jù)庫(kù),看看abc的內(nèi)容是否正確writeback
  d = shelve.open('shelve.db')
  print d['abc']
  d.close()

這個(gè)有一個(gè)潛在的小問(wèn)題,如下:    
>>> import shelve
>>> s = shelve.open('test.dat')
>>> s['x'] = ['a', 'b', 'c']
>>> s['x'].append('d')
>>> s['x']
['a', 'b', 'c']

存儲(chǔ)的d到哪里去了呢?其實(shí)很簡(jiǎn)單,d沒(méi)有寫(xiě)回,你把['a', 'b', 'c']存到了x,當(dāng)你再次讀取s['x']的時(shí)候,s['x']只是一個(gè)拷貝,而你沒(méi)有將拷貝寫(xiě)回,所以當(dāng)你再次讀取s['x']的時(shí)候,它又從源中讀取了一個(gè)拷貝,所以,你新修改的內(nèi)容并不會(huì)出現(xiàn)在拷貝中,解決的辦法就是,第一個(gè)是利用一個(gè)緩存的變量,如下所示    
>>> temp = s['x']
>>> temp.append('d')
>>> s['x'] = temp
>>> s['x']
['a', 'b', 'c', 'd']

python2.4以后有了另外的方法,就是把open方法的writeback參數(shù)的值賦為T(mén)rue,這樣的話(huà),你open后所有的內(nèi)容都將在cache中,當(dāng)你close的時(shí)候,將全部一次性寫(xiě)到硬盤(pán)里面。如果數(shù)據(jù)量不是很大的時(shí)候,建議這么做。

下面是一個(gè)基于shelve的簡(jiǎn)單數(shù)據(jù)庫(kù)的代碼    
#database.py
import sys, shelve
 
def store_person(db):
  """
  Query user for data and store it in the shelf object
  """
  pid = raw_input('Enter unique ID number: ')
  person = {}
  person['name'] = raw_input('Enter name: ')
  person['age'] = raw_input('Enter age: ')
  person['phone'] = raw_input('Enter phone number: ')
  db[pid] = person
 
def lookup_person(db):
  """
  Query user for ID and desired field, and fetch the corresponding data from
  the shelf object
  """
  pid = raw_input('Enter ID number: ')
  field = raw_input('What would you like to know? (name, age, phone) ')
  field = field.strip().lower()
  print field.capitalize() + ':', \
    db[pid][field]
 
def print_help():
  print 'The available commons are: '
  print 'store :Stores information about a person'
  print 'lookup :Looks up a person from ID number'
  print 'quit  :Save changes and exit'
  print '?   :Print this message'
 
def enter_command():
  cmd = raw_input('Enter command (? for help): ')
  cmd = cmd.strip().lower()
  return cmd
 
def main():
  database = shelve.open('database.dat')
  try:  
    while True:
      cmd = enter_command()
      if cmd == 'store':
        store_person(database)
      elif cmd == 'lookup':
        lookup_person(database)
      elif cmd == '?':
        print_help()
      elif cmd == 'quit':
        return
  finally:
    database.close()
if __name__ == '__main__': main()


數(shù)據(jù)分析咨詢(xún)請(qǐng)掃描二維碼

若不方便掃碼,搜微信號(hào):CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線(xiàn)
立即咨詢(xún)
客服在線(xiàn)
立即咨詢(xún)
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個(gè)參數(shù)驗(yàn)證碼對(duì)象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個(gè)配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶(hù)后臺(tái)檢測(cè)極驗(yàn)服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時(shí)表示是新驗(yàn)證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說(shuō)明請(qǐng)參見(jiàn):http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計(jì)時(shí)完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請(qǐng)輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請(qǐng)輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }