def __getitem__(self, alias): if alias in self._connections: return self._connections[alias] django_connections.ensure_defaults(alias) db = self.databases[alias] connection = adbapi.ConnectionPool(db['ENGINE'], db['NAME'], db['USER'], db['PASSWORD']) self._connections[alias] = connection return connection
def named_connection(name, db=DEFAULT_DB_ALIAS): """Initializes a named connection to a database. Django shares open connections to a database that exist in the same thread. This is not appropriate for potentially long-running queries which may need to be canceled. This function creates a new connection to a database using the same options defined in the database settings. Note: Adding the connection to django.db.connections is required because only database aliases are referenced in QuerySets, not the connection itself. When the QuerySet is *executed*, the alias is used to get the connection which must be present. """ # Define a new database alias. temp_db = TEMP_DB_ALIAS_PREFIX.format(name) if temp_db in connections.databases: conn = connections[temp_db] logger.debug('reusing connection for %s', name) else: # Get the settings of the real database being connected to. connections.ensure_defaults(db) # Add new database entry into connections handler so when the query # executes the new connection will be accessible. connections.databases[temp_db] = connections.databases[db] conn = connections[temp_db] logger.debug('initializing connection for %s', name) # Get the backend specific process ID for the query. This will open a # connection to the database if not already open. pid = _get_backend_pid(conn) # Put real database alias and PID in centralized cache so multiple threads # and/or processes can access it. cache = get_cache(settings.QUERY_CACHE) cache.set(temp_db, (db, pid)) return conn
def create_connection(alias=DEFAULT_DB_ALIAS): connections.ensure_defaults(alias) connections.prepare_test_settings(alias) db = connections.databases[alias] backend = load_backend(db['ENGINE']) return backend.DatabaseWrapper(db, alias)