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

(yzsuai) #1

Using Shelves


In other words, shelve is just a go-between; it serializes and deserializes objects so that
they can be placed in string-based DBM files. The net effect is that shelves let you store
nearly arbitrary Python objects on a file by key and fetch them back later with the
same key.


Your scripts never see all of this interfacing, though. Like DBM files, shelves provide
an interface that looks like a dictionary that must be opened. In fact, a shelve is simply
a persistent dictionary of persistent Python objects—the shelve dictionary’s content is
automatically mapped to a file on your computer so that it is retained between program
runs. This is quite a feat, but it’s simpler to your code than it may sound. To gain access
to a shelve, import the module and open your file:


import shelve
dbase = shelve.open("mydbase")

Internally, Python opens a DBM file with the name mydbase, or creates it if it does not
yet exist (it uses the DBM 'c' input/output open mode by default). Assigning to a shelve
key stores an object:


dbase['key'] = object # store object

Internally, this assignment converts the object to a serialized byte stream with pickling
and stores it by key on a DBM file. Indexing a shelve fetches a stored object:


value = dbase['key'] # fetch object

Internally, this index operation loads a string by key from a DBM file and unpickles it
into an in-memory object that is the same as the object originally stored. Most dic-
tionary operations are supported here, too:


len(dbase) # number of items stored
dbase.keys() # stored item key index iterable

And except for a few fine points, that’s really all there is to using a shelve. Shelves are
processed with normal Python dictionary syntax, so there is no new database API to
learn. Moreover, objects stored and fetched from shelves are normal Python objects;
they do not need to be instances of special classes or types to be stored away. That is,
Python’s persistence system is external to the persistent objects themselves.
Table 17-2 summarizes these and other commonly used shelve operations.


Table 17-2. Shelve file operations


Python code Action Description
import shelve Import Get bsddb, gdbm, and so on...whatever is installed
file=shelve.open('filename') Open Create or open an existing shelve’s DBM file
file['key'] = anyvalue Store Create or change the entry for key
value = file['key'] Fetch Load the value for the entry key
count = len(file) Size Return the number of entries stored

1316 | Chapter 17: Databases and Persistence

Free download pdf