shelve -- 用来持久化任意的Python对象(转)

这几天接触了Python中的shelve这个module,感觉比pickle用起来更简单一些,它也是一个用来持久化(序列化)Python对象的简单工具。当我们写程序的时候如果不想用关系数据库那么重量级的东东去存储数据,不妨可以试试用shelve。shelf也是用key来访问的,使用起来和字典类似。shelve其实用anydbm去创建DB并且管理持久化对象的。

创建一个新的shelf

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

复制代码
1 import shelve
2 
3 s = shelve.open('test_shelf.db')
4 try:
5     s['key1'] = { 'int': 10, 'float':9.5, 'string':'Sample data' }
6 finally:
7     s.close()
复制代码

如果想要再次访问这个shelf,只需要再次shelve.open()就可以了,然后我们可以像使用字典一样来使用这个shelf

复制代码
1 import shelve
2 
3 s = shelve.open('test_shelf.db')
4 try:
5     existing = s['key1']
6 finally:
7     s.close()
8 
9 print existing
复制代码

当我们运行以上两个py,我们将得到如下输出:

$ python shelve_create.py
$ python shelve_existing.py

{'int': 10, 'float': 9.5, 'string': 'Sample data'}

dbm这个模块有个限制,它不支持多个应用同一时间往同一个DB进行写操作。所以当我们知道我们的应用如果只进行读操作,我们可以让shelve通过只读方式打开DB:

复制代码
1 import shelve
2 
3 s = shelve.open('test_shelf.db', flag='r')
4 try:
5     existing = s['key1']
6 finally:
7     s.close()
8 
9 print existing
复制代码

当我们的程序试图去修改一个以只读方式打开的DB时,将会抛一个访问错误的异常。异常的具体类型取决于anydbm这个模块在创建DB时所选用的DB。

写回(Write-back)

由于shelve在默认情况下是不会记录待持久化对象的任何修改的,所以我们在shelve.open()时候需要修改默认参数,否则对象的修改不会保存。

复制代码
 1 import shelve
 2 
 3 s = shelve.open('test_shelf.db')
 4 try:
 5     print s['key1']
 6     s['key1']['new_value'] = 'this was not here before'
 7 finally:
 8     s.close()
 9 
10 s = shelve.open('test_shelf.db', writeback=True)
11 try:
12     print s['key1']
13 finally:
14     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。

复制代码
 1 import shelve
 2 
 3 s = shelve.open('test_shelf.db', writeback=True)
 4 try:
 5     print s['key1']
 6     s['key1']['new_value'] = 'this was not here before'
 7     print s['key1']
 8 finally:
 9     s.close()
10 
11 s = shelve.open('test_shelf.db', writeback=True)
12 try:
13     print s['key1']
14 finally:
15     s.close()
复制代码

writeback方式有优点也有缺点。优点是减少了我们出错的概率,并且让对象的持久化对用户更加的透明了;但这种方式并不是所有的情况下都需要,首先,使用writeback以后,shelf在open()的时候会增加额外的内存消耗,并且当DB在close()的时候会将缓存中的每一个对象都写入到DB,这也会带来额外的等待时间。因为shelve没有办法知道缓存中哪些对象修改了,哪些对象没有修改,因此所有的对象都会被写入。

复制代码
1 $ python shelve_create.py
2 $ python shelve_writeback.py
3 
4 {'int': 10, 'float': 9.5, 'string': 'Sample data'}
5 {'int': 10, 'new_value': 'this was not here before', 'float': 9.5, 'string': 'Sample data'}
6 {'int': 10, 'new_value': 'this was not here before', 'float': 9.5, 'string': 'Sample data'}
复制代码

最后再来个复杂一点的例子:

复制代码
 1 #!/bin/env python
 2 
 3 import time
 4 import datetime
 5 import md5
 6 import shelve
 7 
 8 LOGIN_TIME_OUT = 60
 9 db = shelve.open('user_shelve.db', writeback=True)
10 
11 def newuser():
12     global db
13     prompt = "login desired: "
14     while True:
15         name = raw_input(prompt)
16         if name in db:
17             prompt = "name taken, try another: "
18             continue
19         elif len(name) == 0:
20             prompt = "name should not be empty, try another: "
21             continue
22         else:
23             break
24     pwd = raw_input("password: ")
25     db[name] = {"password": md5_digest(pwd), "last_login_time": time.time()}
26     #print '-->', db
27 
28 def olduser():
29     global db
30     name = raw_input("login: ")
31     pwd = raw_input("password: ")
32     try:
33         password = db.get(name).get('password')
34     except AttributeError, e:
35         print "\033[1;31;40mUsername '%s' doesn't existed\033[0m" % name
36         return
37     if md5_digest(pwd) == password:
38         login_time = time.time()
39         last_login_time = db.get(name).get('last_login_time')
40         if login_time - last_login_time < LOGIN_TIME_OUT:
41             print "\033[1;31;40mYou already logged in at: <%s>\033[0m" % datetime.datetime.fromtimestamp(last_login_time).isoformat()
42 
43         db[name]['last_login_time'] = login_time
44         print "\033[1;32;40mwelcome back\033[0m", name
45     else:
46         print "\033[1;31;40mlogin incorrect\033[0m"
47 
48 def md5_digest(plain_pass):
49    return md5.new(plain_pass).hexdigest()
50 
51 def showmenu():
52     #print '>>>', db
53     global db
54     prompt = """
55 (N)ew User Login
56 (E)xisting User Login
57 (Q)uit
58 Enter choice: """
59     done = False
60     while not done:
61         chosen = False
62         while not chosen:
63             try:
64                 choice = raw_input(prompt).strip()[0].lower()
65             except (EOFError, KeyboardInterrupt):
66                 choice = "q"
67             print "\nYou picked: [%s]" % choice
68             if choice not in "neq":
69                 print "invalid option, try again"
70             else:
71                 chosen = True
72 
73         if choice == "q": done = True
74         if choice == "n": newuser()
75         if choice == "e": olduser()
76     db.close()
77 
78 if __name__ == "__main__":
79     showmenu()
复制代码

文章出处:https://www.cnblogs.com/frankzs/p/5949645.html

这几天接触了Python中的shelve这个module,感觉比pickle用起来更简单一些,它也是一个用来持久化(序列化)Python对象的简单工具。当我们写程序的时候如果不想用关系数据库那么重量级的东东去存储数据,不妨可以试试用shelve。shelf也是用key来访问的,使用起来和字典类似。shelve其实用anydbm去创建DB并且管理持久化对象的。

创建一个新的shelf

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

复制代码
1 import shelve
2 
3 s = shelve.open('test_shelf.db')
4 try:
5     s['key1'] = { 'int': 10, 'float':9.5, 'string':'Sample data' }
6 finally:
7     s.close()
复制代码

如果想要再次访问这个shelf,只需要再次shelve.open()就可以了,然后我们可以像使用字典一样来使用这个shelf

复制代码
1 import shelve
2 
3 s = shelve.open('test_shelf.db')
4 try:
5     existing = s['key1']
6 finally:
7     s.close()
8 
9 print existing
复制代码

当我们运行以上两个py,我们将得到如下输出:

$ python shelve_create.py
$ python shelve_existing.py

{'int': 10, 'float': 9.5, 'string': 'Sample data'}

dbm这个模块有个限制,它不支持多个应用同一时间往同一个DB进行写操作。所以当我们知道我们的应用如果只进行读操作,我们可以让shelve通过只读方式打开DB:

复制代码
1 import shelve
2 
3 s = shelve.open('test_shelf.db', flag='r')
4 try:
5     existing = s['key1']
6 finally:
7     s.close()
8 
9 print existing
复制代码

当我们的程序试图去修改一个以只读方式打开的DB时,将会抛一个访问错误的异常。异常的具体类型取决于anydbm这个模块在创建DB时所选用的DB。

写回(Write-back)

由于shelve在默认情况下是不会记录待持久化对象的任何修改的,所以我们在shelve.open()时候需要修改默认参数,否则对象的修改不会保存。

复制代码
 1 import shelve
 2 
 3 s = shelve.open('test_shelf.db')
 4 try:
 5     print s['key1']
 6     s['key1']['new_value'] = 'this was not here before'
 7 finally:
 8     s.close()
 9 
10 s = shelve.open('test_shelf.db', writeback=True)
11 try:
12     print s['key1']
13 finally:
14     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。

复制代码
 1 import shelve
 2 
 3 s = shelve.open('test_shelf.db', writeback=True)
 4 try:
 5     print s['key1']
 6     s['key1']['new_value'] = 'this was not here before'
 7     print s['key1']
 8 finally:
 9     s.close()
10 
11 s = shelve.open('test_shelf.db', writeback=True)
12 try:
13     print s['key1']
14 finally:
15     s.close()
复制代码

writeback方式有优点也有缺点。优点是减少了我们出错的概率,并且让对象的持久化对用户更加的透明了;但这种方式并不是所有的情况下都需要,首先,使用writeback以后,shelf在open()的时候会增加额外的内存消耗,并且当DB在close()的时候会将缓存中的每一个对象都写入到DB,这也会带来额外的等待时间。因为shelve没有办法知道缓存中哪些对象修改了,哪些对象没有修改,因此所有的对象都会被写入。

复制代码
1 $ python shelve_create.py
2 $ python shelve_writeback.py
3 
4 {'int': 10, 'float': 9.5, 'string': 'Sample data'}
5 {'int': 10, 'new_value': 'this was not here before', 'float': 9.5, 'string': 'Sample data'}
6 {'int': 10, 'new_value': 'this was not here before', 'float': 9.5, 'string': 'Sample data'}
复制代码

最后再来个复杂一点的例子:

复制代码
 1 #!/bin/env python
 2 
 3 import time
 4 import datetime
 5 import md5
 6 import shelve
 7 
 8 LOGIN_TIME_OUT = 60
 9 db = shelve.open('user_shelve.db', writeback=True)
10 
11 def newuser():
12     global db
13     prompt = "login desired: "
14     while True:
15         name = raw_input(prompt)
16         if name in db:
17             prompt = "name taken, try another: "
18             continue
19         elif len(name) == 0:
20             prompt = "name should not be empty, try another: "
21             continue
22         else:
23             break
24     pwd = raw_input("password: ")
25     db[name] = {"password": md5_digest(pwd), "last_login_time": time.time()}
26     #print '-->', db
27 
28 def olduser():
29     global db
30     name = raw_input("login: ")
31     pwd = raw_input("password: ")
32     try:
33         password = db.get(name).get('password')
34     except AttributeError, e:
35         print "\033[1;31;40mUsername '%s' doesn't existed\033[0m" % name
36         return
37     if md5_digest(pwd) == password:
38         login_time = time.time()
39         last_login_time = db.get(name).get('last_login_time')
40         if login_time - last_login_time < LOGIN_TIME_OUT:
41             print "\033[1;31;40mYou already logged in at: <%s>\033[0m" % datetime.datetime.fromtimestamp(last_login_time).isoformat()
42 
43         db[name]['last_login_time'] = login_time
44         print "\033[1;32;40mwelcome back\033[0m", name
45     else:
46         print "\033[1;31;40mlogin incorrect\033[0m"
47 
48 def md5_digest(plain_pass):
49    return md5.new(plain_pass).hexdigest()
50 
51 def showmenu():
52     #print '>>>', db
53     global db
54     prompt = """
55 (N)ew User Login
56 (E)xisting User Login
57 (Q)uit
58 Enter choice: """
59     done = False
60     while not done:
61         chosen = False
62         while not chosen:
63             try:
64                 choice = raw_input(prompt).strip()[0].lower()
65             except (EOFError, KeyboardInterrupt):
66                 choice = "q"
67             print "\nYou picked: [%s]" % choice
68             if choice not in "neq":
69                 print "invalid option, try again"
70             else:
71                 chosen = True
72 
73         if choice == "q": done = True
74         if choice == "n": newuser()
75         if choice == "e": olduser()
76     db.close()
77 
78 if __name__ == "__main__":
79     showmenu()
复制代码

猜你喜欢

转载自www.cnblogs.com/Suoha2018/p/10345416.html