| 1 |
"""Generic interface to all dbm clones. |
| 2 |
|
| 3 |
Instead of |
| 4 |
|
| 5 |
import dbm |
| 6 |
d = dbm.open(file, 'w', 0666) |
| 7 |
|
| 8 |
use |
| 9 |
|
| 10 |
import anydbm |
| 11 |
d = anydbm.open(file, 'w') |
| 12 |
|
| 13 |
The returned object is a dbhash, gdbm, dbm or dumbdbm object, |
| 14 |
dependent on the type of database being opened (determined by whichdb |
| 15 |
module) in the case of an existing dbm. If the dbm does not exist and |
| 16 |
the create or new flag ('c' or 'n') was specified, the dbm type will |
| 17 |
be determined by the availability of the modules (tested in the above |
| 18 |
order). |
| 19 |
|
| 20 |
It has the following interface (key and data are strings): |
| 21 |
|
| 22 |
d[key] = data # store data at key (may override data at |
| 23 |
# existing key) |
| 24 |
data = d[key] # retrieve data at key (raise KeyError if no |
| 25 |
# such key) |
| 26 |
del d[key] # delete data stored at key (raises KeyError |
| 27 |
# if no such key) |
| 28 |
flag = key in d # true if the key exists |
| 29 |
list = d.keys() # return a list of all existing keys (slow!) |
| 30 |
|
| 31 |
Future versions may change the order in which implementations are |
| 32 |
tested for existence, and add interfaces to other dbm-like |
| 33 |
implementations. |
| 34 |
""" |
| 35 |
|
| 36 |
class error(Exception): |
| 37 |
pass |
| 38 |
|
| 39 |
_names = ['dbhash', 'gdbm', 'dbm', 'dumbdbm'] |
| 40 |
_errors = [error] |
| 41 |
_defaultmod = None |
| 42 |
|
| 43 |
for _name in _names: |
| 44 |
try: |
| 45 |
_mod = __import__(_name) |
| 46 |
except ImportError: |
| 47 |
continue |
| 48 |
if not _defaultmod: |
| 49 |
_defaultmod = _mod |
| 50 |
_errors.append(_mod.error) |
| 51 |
|
| 52 |
if not _defaultmod: |
| 53 |
raise ImportError, "no dbm clone found; tried %s" % _names |
| 54 |
|
| 55 |
error = tuple(_errors) |
| 56 |
|
| 57 |
def open(file, flag='r', mode=0666): |
| 58 |
"""Open or create database at path given by *file*. |
| 59 |
|
| 60 |
Optional argument *flag* can be 'r' (default) for read-only access, 'w' |
| 61 |
for read-write access of an existing database, 'c' for read-write access |
| 62 |
to a new or existing database, and 'n' for read-write access to a new |
| 63 |
database. |
| 64 |
|
| 65 |
Note: 'r' and 'w' fail if the database doesn't exist; 'c' creates it |
| 66 |
only if it doesn't exist; and 'n' always creates a new database. |
| 67 |
""" |
| 68 |
|
| 69 |
|
| 70 |
from whichdb import whichdb |
| 71 |
result=whichdb(file) |
| 72 |
if result is None: |
| 73 |
|
| 74 |
if 'c' in flag or 'n' in flag: |
| 75 |
|
| 76 |
|
| 77 |
mod = _defaultmod |
| 78 |
else: |
| 79 |
raise error, "need 'c' or 'n' flag to open new db" |
| 80 |
elif result == "": |
| 81 |
|
| 82 |
raise error, "db type could not be determined" |
| 83 |
else: |
| 84 |
mod = __import__(result) |
| 85 |
return mod.open(file, flag, mode) |