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

(yzsuai) #1

none of the partially complete work it has done is retained. In fact, ZODB supports
general database undo operations.


Pulling persistent objects back from ZODB in another session or program is just as
straightforward: reopen the database as before and index the root to fetch objects back
into memory. Like shelves, the database root supports dictionary interfaces—it may
be indexed, has dictionary methods and a length, and so on:


...\PP4E\Dbase\Zodb-2.x> python
>>> from ZODB import FileStorage, DB
>>> storage = FileStorage.FileStorage(r'C:\temp\mydb.fs')
>>> db = DB(storage)
>>> connection = db.open()
>>> root = connection.root() # connect

>>> len(root), root.keys() # size, index
(4 ['mylist', 'mystr', 'mytuple', 'mydict'])

>>> root['mylist'] # fetch objects
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> root['mydict']
{'job': ('dev', 'mgr'), 'age': 42, 'name': ['Bob', 'Doe']}

>>> root['mydict']['name'][-1] # Bob's last name
'Doe'

Because the database root looks just like a dictionary, we can process it with normal
dictionary code—stepping through the keys list to scan record by record, for instance:


>>> for key in root.keys():
print('%s => %s' % (key.ljust(10), root[key]))

mylist => [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
mystr => spamspamspam
mytuple => (1, 'spam', 4, 'YOU')
mydict => {'job': ('dev', 'mgr'), 'age': 42, 'name': ['Bob', 'Doe']}

Also like pickling and shelves, ZODB supports storage and retrieval of class instance
objects, though they must inherit from a superclass which provides required protocol
and intercepts attribute changes in order to flush them to disk automatically:


from persistent import Persistent
class Person(Persistent):
def __init__(self, name, job=None, rate=0):
self.name = name
self.job = job
self.rate = rate
def changeRate(self, newrate):
self.rate = newrate # automatically updates database

When changing ZODB persistent class instances, in-memory attribute changes are
automatically written back to the database. Other types of changes, such as in-place
appends and key assignments, still require reassignment to the original key as in shelves


1328 | Chapter 17: Databases and Persistence

Free download pdf