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

(yzsuai) #1
...\PP4E\Preview> python make_db_pickle.py
...\PP4E\Preview> python dump_db_pickle.py
bob =>
{'pay': 30000, 'job': 'dev', 'age': 42, 'name': 'Bob Smith'}
sue =>
{'pay': 40000, 'job': 'hdw', 'age': 45, 'name': 'Sue Jones'}
tom =>
{'pay': 0, 'job': None, 'age': 50, 'name': 'Tom'}
Sue Jones

Updating with a pickle file is similar to a manually formatted file, except that Python
is doing all of the formatting work for us. Example 1-7 shows how.


Example 1-7. PP4E\Preview\update-db-pickle.py


import pickle
dbfile = open('people-pickle', 'rb')
db = pickle.load(dbfile)
dbfile.close()


db['sue']['pay'] *= 1.10
db['tom']['name'] = 'Tom Tom'


dbfile = open('people-pickle', 'wb')
pickle.dump(db, dbfile)
dbfile.close()


Notice how the entire database is written back to the file after the records are changed
in memory, just as for the manually formatted approach; this might become slow for
very large databases, but we’ll ignore this for the moment. Here are our update and
dump scripts in action—as in the prior section, Sue’s pay and Tom’s name change
between scripts because they are written back to a file (this time, a pickle file):


...\PP4E\Preview> python update_db_pickle.py
...\PP4E\Preview> python dump_db_pickle.py
bob =>
{'pay': 30000, 'job': 'dev', 'age': 42, 'name': 'Bob Smith'}
sue =>
{'pay': 44000.0, 'job': 'hdw', 'age': 45, 'name': 'Sue Jones'}
tom =>
{'pay': 0, 'job': None, 'age': 50, 'name': 'Tom Tom'}
Sue Jones

As we’ll learn in Chapter 17, the Python pickling system supports nearly arbitrary object
types—lists, dictionaries, class instances, nested structures, and more. There, we’ll also
learn about the pickler’s text and binary storage protocols; as of Python 3, all protocols
use bytes objects to represent pickled data, which in turn requires pickle files to be
opened in binary mode for all protocols. As we’ll see later in this chapter, the pickler
and its data format also underlie shelves and ZODB databases, and pickled class in-
stances provide both data and behavior for objects stored.


In fact, pickling is more general than these examples may imply. Because they accept
any object that provides an interface compatible with files, pickling and unpickling may


Step 2: Storing Records Persistently | 21
Free download pdf