|
15 | 15 | # BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE, |
16 | 16 | # SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. |
17 | 17 | # |
18 | | -# $Id: __init__.py,v 1.29 2004-11-03 01:34:21 richard Exp $ |
| 18 | +# $Id: __init__.py,v 1.30 2004-11-18 15:50:37 a1s Exp $ |
19 | 19 |
|
20 | 20 | '''Container for the hyperdb storage backend implementations. |
21 | 21 | ''' |
22 | 22 | __docformat__ = 'restructuredtext' |
23 | 23 |
|
| 24 | +import sys |
| 25 | + |
| 26 | +# These names are used to suppress import errors. |
| 27 | +# If get_backend raises an ImportError with appropriate |
| 28 | +# module name, have_backend quietly returns False. |
| 29 | +# Otherwise the error is reraised. |
24 | 30 | _modules = { |
25 | 31 | 'mysql': 'MySQLdb', |
26 | 32 | 'postgresql': 'psycopg', |
27 | 33 | } |
28 | 34 |
|
29 | 35 | def get_backend(name): |
30 | 36 | '''Get a specific backend by name.''' |
31 | | - return __import__('back_%s'%name, globals()) |
| 37 | + vars = globals() |
| 38 | + # if requested backend has been imported yet, return current instance |
| 39 | + if vars.has_key(name): |
| 40 | + return vars[name] |
| 41 | + # import the backend module |
| 42 | + module_name = 'back_%s' % name |
| 43 | + try: |
| 44 | + module = __import__(module_name, vars) |
| 45 | + except: |
| 46 | + # import failed, but the (empty) module is already |
| 47 | + # placed in sys.modules and package globals; |
| 48 | + # next import would success although the module is unusable |
| 49 | + del sys.modules['.'.join((__name__, module_name))] |
| 50 | + del vars[module_name] |
| 51 | + raise |
| 52 | + else: |
| 53 | + vars[name] = module |
| 54 | + return module |
32 | 55 |
|
33 | 56 | def have_backend(name): |
34 | 57 | '''Is backend "name" available?''' |
35 | | - module = _modules.get(name, name) |
36 | 58 | try: |
37 | 59 | get_backend(name) |
38 | 60 | return 1 |
39 | 61 | except ImportError, e: |
40 | | - if not str(e).startswith('No module named %s'%module): |
| 62 | + global _modules |
| 63 | + if not str(e).startswith('No module named %s' % _modules[name]): |
41 | 64 | raise |
42 | 65 | return 0 |
43 | 66 |
|
44 | 67 | def list_backends(): |
45 | | - '''List all available backend names.''' |
| 68 | + '''List all available backend names. |
| 69 | +
|
| 70 | + This function has side-effect of registering backward-compatible |
| 71 | + globals for all available backends. |
| 72 | +
|
| 73 | + ''' |
46 | 74 | l = [] |
47 | 75 | for name in 'anydbm', 'mysql', 'sqlite', 'metakit', 'postgresql': |
48 | 76 | if have_backend(name): |
49 | 77 | l.append(name) |
50 | 78 | return l |
51 | 79 |
|
52 | | -# vim: set filetype=python ts=4 sw=4 et si |
| 80 | +# vim: set filetype=python sts=4 sw=4 et si : |
0 commit comments