Back to index

python3.2  3.2.2
Namespaces | Classes | Functions | Variables
dbm Namespace Reference

Namespaces

namespace  dumb
namespace  gnu
namespace  ndbm

Classes

class  error

Functions

def open
def whichdb

Variables

list __all__ = ['open', 'whichdb', 'error']
list _names = ['dbm.gnu', 'dbm.ndbm', 'dbm.dumb']
 _defaultmod = None
dictionary _modules = {}
tuple error = (error, IOError)

Detailed Description

Generic interface to all dbm clones.

Use

import dbm
d = dbm.open(file, 'w', 0o666)

The returned object is a dbm.gnu, dbm.ndbm or dbm.dumb object, dependent on the
type of database being opened (determined by the whichdb function) in the case
of an existing dbm. If the dbm does not exist and the create or new flag ('c'
or 'n') was specified, the dbm type will be determined by the availability of
the modules (tested in the above order).

It has the following interface (key and data are strings):

d[key] = data   # store data at key (may override data at
                # existing key)
data = d[key]   # retrieve data at key (raise KeyError if no
                # such key)
del d[key]      # delete data stored at key (raises KeyError
                # if no such key)
flag = key in d # true if the key exists
list = d.keys() # return a list of all existing keys (slow!)

Future versions may change the order in which implementations are
tested for existence, and add interfaces to other dbm-like
implementations.

Function Documentation

def dbm.open (   file,
  flag = 'r',
  mode = 0o666 
)
Open or create database at path given by *file*.

Optional argument *flag* can be 'r' (default) for read-only access, 'w'
for read-write access of an existing database, 'c' for read-write access
to a new or existing database, and 'n' for read-write access to a new
database.

Note: 'r' and 'w' fail if the database doesn't exist; 'c' creates it
only if it doesn't exist; and 'n' always creates a new database.

Definition at line 48 of file __init__.py.

00048 
00049 def open(file, flag='r', mode=0o666):
00050     """Open or create database at path given by *file*.
00051 
00052     Optional argument *flag* can be 'r' (default) for read-only access, 'w'
00053     for read-write access of an existing database, 'c' for read-write access
00054     to a new or existing database, and 'n' for read-write access to a new
00055     database.
00056 
00057     Note: 'r' and 'w' fail if the database doesn't exist; 'c' creates it
00058     only if it doesn't exist; and 'n' always creates a new database.
00059     """
00060     global _defaultmod
00061     if _defaultmod is None:
00062         for name in _names:
00063             try:
00064                 mod = __import__(name, fromlist=['open'])
00065             except ImportError:
00066                 continue
00067             if not _defaultmod:
00068                 _defaultmod = mod
00069             _modules[name] = mod
00070         if not _defaultmod:
00071             raise ImportError("no dbm clone found; tried %s" % _names)
00072 
00073     # guess the type of an existing database, if not creating a new one
00074     result = whichdb(file) if 'n' not in flag else None
00075     if result is None:
00076         # db doesn't exist or 'n' flag was specified to create a new db
00077         if 'c' in flag or 'n' in flag:
00078             # file doesn't exist and the new flag was used so use default type
00079             mod = _defaultmod
00080         else:
00081             raise error[0]("need 'c' or 'n' flag to open new db")
00082     elif result == "":
00083         # db type cannot be determined
00084         raise error[0]("db type could not be determined")
00085     elif result not in _modules:
00086         raise error[0]("db type is {0}, but the module is not "
00087                        "available".format(result))
00088     else:
00089         mod = _modules[result]
00090     return mod.open(file, flag, mode)
00091 

Here is the caller graph for this function:

def dbm.whichdb (   filename)
Guess which db package to use to open a db file.

Return values:

- None if the database file can't be read;
- empty string if the file can be read but can't be recognized
- the name of the dbm submodule (e.g. "ndbm" or "gnu") if recognized.

Importing the given module may still fail, and opening the
database using that module may still fail.

Definition at line 92 of file __init__.py.

00092 
00093 def whichdb(filename):
00094     """Guess which db package to use to open a db file.
00095 
00096     Return values:
00097 
00098     - None if the database file can't be read;
00099     - empty string if the file can be read but can't be recognized
00100     - the name of the dbm submodule (e.g. "ndbm" or "gnu") if recognized.
00101 
00102     Importing the given module may still fail, and opening the
00103     database using that module may still fail.
00104     """
00105 
00106     # Check for ndbm first -- this has a .pag and a .dir file
00107     try:
00108         f = io.open(filename + ".pag", "rb")
00109         f.close()
00110         # dbm linked with gdbm on OS/2 doesn't have .dir file
00111         if not (ndbm.library == "GNU gdbm" and sys.platform == "os2emx"):
00112             f = io.open(filename + ".dir", "rb")
00113             f.close()
00114         return "dbm.ndbm"
00115     except IOError:
00116         # some dbm emulations based on Berkeley DB generate a .db file
00117         # some do not, but they should be caught by the bsd checks
00118         try:
00119             f = io.open(filename + ".db", "rb")
00120             f.close()
00121             # guarantee we can actually open the file using dbm
00122             # kind of overkill, but since we are dealing with emulations
00123             # it seems like a prudent step
00124             if ndbm is not None:
00125                 d = ndbm.open(filename)
00126                 d.close()
00127                 return "dbm.ndbm"
00128         except IOError:
00129             pass
00130 
00131     # Check for dumbdbm next -- this has a .dir and a .dat file
00132     try:
00133         # First check for presence of files
00134         os.stat(filename + ".dat")
00135         size = os.stat(filename + ".dir").st_size
00136         # dumbdbm files with no keys are empty
00137         if size == 0:
00138             return "dbm.dumb"
00139         f = io.open(filename + ".dir", "rb")
00140         try:
00141             if f.read(1) in (b"'", b'"'):
00142                 return "dbm.dumb"
00143         finally:
00144             f.close()
00145     except (OSError, IOError):
00146         pass
00147 
00148     # See if the file exists, return None if not
00149     try:
00150         f = io.open(filename, "rb")
00151     except IOError:
00152         return None
00153 
00154     # Read the start of the file -- the magic number
00155     s16 = f.read(16)
00156     f.close()
00157     s = s16[0:4]
00158 
00159     # Return "" if not at least 4 bytes
00160     if len(s) != 4:
00161         return ""
00162 
00163     # Convert to 4-byte int in native byte order -- return "" if impossible
00164     try:
00165         (magic,) = struct.unpack("=l", s)
00166     except struct.error:
00167         return ""
00168 
00169     # Check for GNU dbm
00170     if magic == 0x13579ace:
00171         return "dbm.gnu"
00172 
00173     # Later versions of Berkeley db hash file have a 12-byte pad in
00174     # front of the file type
00175     try:
00176         (magic,) = struct.unpack("=l", s16[-4:])
00177     except struct.error:
00178         return ""
00179 
00180     # Unknown
00181     return ""
00182 

Here is the caller graph for this function:


Variable Documentation

list dbm.__all__ = ['open', 'whichdb', 'error']

Definition at line 30 of file __init__.py.

Definition at line 42 of file __init__.py.

Definition at line 43 of file __init__.py.

list dbm._names = ['dbm.gnu', 'dbm.ndbm', 'dbm.dumb']

Definition at line 41 of file __init__.py.

tuple dbm.error = (error, IOError)

Definition at line 45 of file __init__.py.