diff --git a/django/db/__init__.py b/django/db/__init__.py index 077e1b2d8b..885ca41318 100644 --- a/django/db/__init__.py +++ b/django/db/__init__.py @@ -2,7 +2,6 @@ import warnings from django.conf import settings from django.core import signals -from django.core.exceptions import ImproperlyConfigured from django.db.utils import (DEFAULT_DB_ALIAS, DataError, OperationalError, IntegrityError, InternalError, ProgrammingError, NotSupportedError, DatabaseError, @@ -13,11 +12,7 @@ from django.utils.functional import cached_property __all__ = ('backend', 'connection', 'connections', 'router', 'DatabaseError', 'IntegrityError', 'DEFAULT_DB_ALIAS') - -if settings.DATABASES and DEFAULT_DB_ALIAS not in settings.DATABASES: - raise ImproperlyConfigured("You must define a '%s' database" % DEFAULT_DB_ALIAS) - -connections = ConnectionHandler(settings.DATABASES) +connections = ConnectionHandler() router = ConnectionRouter(settings.DATABASE_ROUTERS) diff --git a/django/db/utils.py b/django/db/utils.py index e84060f9b3..0bc72fd768 100644 --- a/django/db/utils.py +++ b/django/db/utils.py @@ -6,6 +6,7 @@ import warnings from django.conf import settings from django.core.exceptions import ImproperlyConfigured +from django.utils.functional import cached_property from django.utils.importlib import import_module from django.utils.module_loading import import_by_path from django.utils._os import upath @@ -138,16 +139,27 @@ class ConnectionDoesNotExist(Exception): class ConnectionHandler(object): - def __init__(self, databases): - if not databases: - self.databases = { + def __init__(self, databases=None): + """ + databases is an optional dictionary of database definitions (structured + like settings.DATABASES). + """ + self._databases = databases + self._connections = local() + + @cached_property + def databases(self): + if self._databases is None: + self._databases = settings.DATABASES + if self._databases == {}: + self._databases = { DEFAULT_DB_ALIAS: { 'ENGINE': 'django.db.backends.dummy', }, } - else: - self.databases = databases - self._connections = local() + if DEFAULT_DB_ALIAS not in self._databases: + raise ImproperlyConfigured("You must define a '%s' database" % DEFAULT_DB_ALIAS) + return self._databases def ensure_defaults(self, alias): """