Tidied djang.db.utils.load_backend().

Removed an unneeded EnvironmentError catching and used
"raise from exc" syntax.
This commit is contained in:
Tim Graham 2017-01-24 08:33:26 -05:00 committed by GitHub
parent 435e4bf38e
commit a87d6b69a7
2 changed files with 14 additions and 18 deletions

View File

@ -111,23 +111,19 @@ def load_backend(backend_name):
return import_module('%s.base' % backend_name) return import_module('%s.base' % backend_name)
except ImportError as e_user: except ImportError as e_user:
# The database backend wasn't found. Display a helpful error message # The database backend wasn't found. Display a helpful error message
# listing all possible (built-in) database backends. # listing all built-in database backends.
backend_dir = os.path.join(os.path.dirname(__file__), 'backends') backend_dir = os.path.join(os.path.dirname(__file__), 'backends')
try:
builtin_backends = [ builtin_backends = [
name for _, name, ispkg in pkgutil.iter_modules([backend_dir]) name for _, name, ispkg in pkgutil.iter_modules([backend_dir])
if ispkg and name not in {'base', 'dummy', 'postgresql_psycopg2'} if ispkg and name not in {'base', 'dummy', 'postgresql_psycopg2'}
] ]
except EnvironmentError: if backend_name not in ['django.db.backends.%s' % b for b in builtin_backends]:
builtin_backends = []
if backend_name not in ['django.db.backends.%s' % b for b in
builtin_backends]:
backend_reprs = map(repr, sorted(builtin_backends)) backend_reprs = map(repr, sorted(builtin_backends))
error_msg = ("%r isn't an available database backend.\n" raise ImproperlyConfigured(
"Try using 'django.db.backends.XXX', where XXX " "%r isn't an available database backend.\n"
"is one of:\n %s\nError was: %s" % "Try using 'django.db.backends.XXX', where XXX is one of:\n"
(backend_name, ", ".join(backend_reprs), e_user)) " %s" % (backend_name, ", ".join(backend_reprs))
raise ImproperlyConfigured(error_msg) ) from e_user
else: else:
# If there's some other error, this must be an error in Django # If there's some other error, this must be an error in Django
raise raise

View File

@ -8,8 +8,8 @@ class TestLoadBackend(SimpleTestCase):
msg = ( msg = (
"'foo' isn't an available database backend.\n" "'foo' isn't an available database backend.\n"
"Try using 'django.db.backends.XXX', where XXX is one of:\n" "Try using 'django.db.backends.XXX', where XXX is one of:\n"
" 'mysql', 'oracle', 'postgresql', 'sqlite3'\n" " 'mysql', 'oracle', 'postgresql', 'sqlite3'"
"Error was: No module named 'foo'"
) )
with self.assertRaisesMessage(ImproperlyConfigured, msg): with self.assertRaisesMessage(ImproperlyConfigured, msg) as cm:
load_backend('foo') load_backend('foo')
self.assertEqual(str(cm.exception.__cause__), "No module named 'foo'")