[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1
>>> dbase = shelve.open("mydbase")
>>> object1 = ['The', 'bright', ('side', 'of'), ['life']]
>>> object2 = {'name': 'Brian', 'age': 33, 'motto': object1}

>>> dbase['brian'] = object2
>>> dbase['knight'] = {'name': 'Knight', 'motto': 'Ni!'}
>>> dbase.close()

Here, we open a shelve and store two fairly complex dictionary and list data structures
away permanently by simply assigning them to shelve keys. Because shelve uses
pickle internally, almost anything goes here—the trees of nested objects are automat-
ically serialized into strings for storage. To fetch them back, just reopen the shelve and
index:


C:\...\PP4E\Dbase> python
>>> import shelve
>>> dbase = shelve.open("mydbase")
>>> len(dbase) # entries
2

>>> dbase.keys() # index
KeysView(<shelve.DbfilenameShelf object at 0x0181F630>)

>>> list(dbase.keys())
['brian', 'knight']

>>> dbase['knight'] # fetch
{'motto': 'Ni!', 'name': 'Knight'}

>>> for row in dbase.keys(): # .keys() is optional
... print(row, '=>')
... for field in dbase[row].keys():
... print(' ', field, '=', dbase[row][field])

brian =>
motto = ['The', 'bright', ('side', 'of'), ['life']]
age = 33
name = Brian
knight =>
motto = Ni!
name = Knight

The nested loops at the end of this session step through nested dictionaries—the outer
scans the shelve and the inner scans the objects stored in the shelve (both could use
key iterators and omit their .keys() calls). The crucial point to notice is that we’re using
normal Python syntax, both to store and to fetch these persistent objects, as well as to
process them after loading. It’s persistent Python data on disk.


Storing Class Instances in Shelves


One of the more useful kinds of objects to store in a shelve is a class instance. Because
its attributes record state and its inherited methods define behavior, persistent class


1318 | Chapter 17: Databases and Persistence

Free download pdf