Skip to content

Commit ab33fd9

Browse files
author
Alexander Smishlajev
committed
fix: second call to get_backend() succeeded...
...even if the backend is not available. get_backend() (and hence has_backend and list_backends) registers backward-compatible globals for available backends and uses these globals to skip import if already done. fix vim modeline
1 parent 059cc8d commit ab33fd9

File tree

1 file changed

+34
-6
lines changed

1 file changed

+34
-6
lines changed

roundup/backends/__init__.py

Lines changed: 34 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,38 +15,66 @@
1515
# BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
1616
# SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
1717
#
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 $
1919

2020
'''Container for the hyperdb storage backend implementations.
2121
'''
2222
__docformat__ = 'restructuredtext'
2323

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.
2430
_modules = {
2531
'mysql': 'MySQLdb',
2632
'postgresql': 'psycopg',
2733
}
2834

2935
def get_backend(name):
3036
'''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
3255

3356
def have_backend(name):
3457
'''Is backend "name" available?'''
35-
module = _modules.get(name, name)
3658
try:
3759
get_backend(name)
3860
return 1
3961
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]):
4164
raise
4265
return 0
4366

4467
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+
'''
4674
l = []
4775
for name in 'anydbm', 'mysql', 'sqlite', 'metakit', 'postgresql':
4876
if have_backend(name):
4977
l.append(name)
5078
return l
5179

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

Comments
 (0)