Python django.db.connection.ensure_connection() Examples

The following are 22 code examples of django.db.connection.ensure_connection(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.db.connection , or try the search function .
Example #1
Source File: plugin.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def _ensureConnection(self):
        # If connection is already made close it.
        from django.db import connection

        if connection.connection is not None:
            connection.close()

        # Loop forever until a connection can be made.
        while True:
            try:
                connection.ensure_connection()
            except Exception:
                log.err(
                    _why=(
                        "Error starting: "
                        "Connection to database cannot be established."
                    )
                )
                time.sleep(1)
            else:
                # Connection made, now close it.
                connection.close()
                break 
Example #2
Source File: checks.py    From python-dockerflow with Mozilla Public License 2.0 6 votes vote down vote up
def check_database_connected(app_configs, **kwargs):
    """
    A Django check to see if connecting to the configured default
    database backend succeeds.
    """
    errors = []

    try:
        connection.ensure_connection()
    except OperationalError as e:
        msg = "Could not connect to database: {!s}".format(e)
        errors.append(checks.Error(msg, id=health.ERROR_CANNOT_CONNECT_DATABASE))
    except ImproperlyConfigured as e:
        msg = 'Datbase misconfigured: "{!s}"'.format(e)
        errors.append(checks.Error(msg, id=health.ERROR_MISCONFIGURED_DATABASE))
    else:
        if not connection.is_usable():
            errors.append(
                checks.Error(
                    "Database connection is not usable",
                    id=health.ERROR_UNUSABLE_DATABASE,
                )
            )

    return errors 
Example #3
Source File: wait_for_db.py    From doccano with MIT License 6 votes vote down vote up
def handle(self, *args, **options):
        max_retries = options['max_retries']
        poll_seconds = options['poll_seconds']

        for retry in range(max_retries):
            try:
                connection.ensure_connection()
            except OperationalError as ex:
                self.stdout.write(
                    'Database unavailable on attempt {attempt}/{max_retries}:'
                    ' {error}'.format(
                        attempt=retry + 1,
                        max_retries=max_retries,
                        error=ex))
                time.sleep(poll_seconds)
            else:
                break
        else:
            self.stdout.write(self.style.ERROR('Database unavailable'))
            sys.exit(1) 
Example #4
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_ignores_connection_configuration_queries(self):
        real_ensure_connection = connection.ensure_connection
        connection.close()

        def make_configuration_query():
            is_opening_connection = connection.connection is None
            real_ensure_connection()

            if is_opening_connection:
                # Avoid infinite recursion. Creating a cursor calls
                # ensure_connection() which is currently mocked by this method.
                connection.cursor().execute('SELECT 1' + connection.features.bare_select_suffix)

        ensure_connection = 'django.db.backends.base.base.BaseDatabaseWrapper.ensure_connection'
        with mock.patch(ensure_connection, side_effect=make_configuration_query):
            with self.assertNumQueries(1):
                list(Car.objects.all()) 
Example #5
Source File: test_orm.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_leaves_preexisting_connections_open(self):
        # Ensure there's a database connection to begin with.
        connection.ensure_connection()

        # No transaction has been entered (what Django calls an atomic block),
        # but the connection has been established.
        self.assertFalse(connection.in_atomic_block)
        self.expectThat(connection.connection, Not(Is(None)))

        # Call a function via the `transactional` decorator.
        decorated_function = orm.transactional(lambda: None)
        decorated_function()

        # After the decorated function has returned the transaction has
        # been exited, but the preexisting connection remains open.
        self.assertFalse(connection.in_atomic_block)
        self.expectThat(connection.connection, Not(Is(None))) 
Example #6
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_ignores_connection_configuration_queries(self):
        real_ensure_connection = connection.ensure_connection
        connection.close()

        def make_configuration_query():
            is_opening_connection = connection.connection is None
            real_ensure_connection()

            if is_opening_connection:
                # Avoid infinite recursion. Creating a cursor calls
                # ensure_connection() which is currently mocked by this method.
                connection.cursor().execute('SELECT 1' + connection.features.bare_select_suffix)

        ensure_connection = 'django.db.backends.base.base.BaseDatabaseWrapper.ensure_connection'
        with mock.patch(ensure_connection, side_effect=make_configuration_query):
            with self.assertNumQueries(1):
                list(Car.objects.all()) 
Example #7
Source File: test_orm.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_disconnects_and_reconnects_if_not_usable(self):
        connection.ensure_connection()
        preexisting_connection = connection.connection

        connection.errors_occurred = True
        self.patch(connection, "is_usable").return_value = False

        self.assertThat(connection.connection, Not(Is(None)))
        with orm.connected():
            self.assertThat(
                connection.connection, Not(Is(preexisting_connection))
            )
            self.assertThat(connection.connection, Not(Is(None)))

        self.assertThat(connection.connection, Not(Is(preexisting_connection)))
        self.assertThat(connection.connection, Not(Is(None))) 
Example #8
Source File: orm.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def connected():
    """Context manager that ensures we're connected to the database.

    If there is not yet a connection to the database, this will connect on
    entry and disconnect on exit. Preexisting connections will be left alone.

    If the preexisting connection is not usable it is closed and a new
    connection is made.
    """
    if connection.connection is None:
        connection.close_if_unusable_or_obsolete()
        connection.ensure_connection()
        try:
            yield
        finally:
            connection.close()
    elif connection.is_usable():
        yield
    else:
        # Connection is not usable, so we disconnect and reconnect. Since
        # the connection was previously connected we do not disconnect this
        # new connection.
        connection.close_if_unusable_or_obsolete()
        connection.ensure_connection()
        yield 
Example #9
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_client_encoding(self):
        """Client encoding is set correctly."""
        connection.ensure_connection()
        self.assertEqual(connection.connection.encoding, 'UTF-8')
        self.assertEqual(connection.connection.nencoding, 'UTF-8') 
Example #10
Source File: test_orm.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_closes_connections_even_if_open_on_entry(self):
        for alias in connections:
            connections[alias].ensure_connection()
        for alias in connections:
            self.assertOpen(alias)
        with FullyConnected():
            for alias in connections:
                self.assertOpen(alias)
        for alias in connections:
            self.assertClosed(alias) 
Example #11
Source File: test_orm.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_exit_closes_open_connections(self):
        self.addCleanup(connection.close)
        connection.ensure_connection()
        self.assertThat(connection.connection, Not(Is(None)))
        context = ExclusivelyConnected()
        context.__exit__()
        self.assertThat(connection.connection, Is(None)) 
Example #12
Source File: test_orm.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_enter_blows_up_if_there_are_open_connections(self):
        self.addCleanup(connection.close)
        connection.ensure_connection()
        context = ExclusivelyConnected()
        self.assertRaises(AssertionError, context.__enter__) 
Example #13
Source File: test_orm.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_exit_removes_block_on_database_connections(self):
        with TotallyDisconnected():
            self.assertRaises(RuntimeError, getattr, connection, "connect")
        connection.ensure_connection() 
Example #14
Source File: test_orm.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_leaves_preexisting_connections_alone(self):
        connection.ensure_connection()
        preexisting_connection = connection.connection

        self.assertThat(connection.connection, Not(Is(None)))
        with orm.connected():
            self.assertThat(connection.connection, Is(preexisting_connection))
        self.assertThat(connection.connection, Is(preexisting_connection)) 
Example #15
Source File: orm.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def __enter__(self):
        """Assert that no connections are yet open."""
        for alias in connections:
            connections[alias].ensure_connection() 
Example #16
Source File: __init__.py    From django-dbconn-retry with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_prehook(self) -> None:
        cb = Mock(name='pre_reconnect_hook')
        ddr.pre_reconnect.connect(cb)
        self.assertRaises(OperationalError, connection.ensure_connection)
        self.assertTrue(cb.called)
        del connection._connection_retries 
Example #17
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_client_encoding(self):
        """Client encoding is set correctly."""
        connection.ensure_connection()
        self.assertEqual(connection.connection.encoding, 'UTF-8')
        self.assertEqual(connection.connection.nencoding, 'UTF-8') 
Example #18
Source File: sqlalchemy_utils.py    From zulip with Apache License 2.0 5 votes vote down vote up
def get_sqlalchemy_connection() -> sqlalchemy.engine.base.Connection:
    global sqlalchemy_engine
    if sqlalchemy_engine is None:
        def get_dj_conn() -> TimeTrackingConnection:
            connection.ensure_connection()
            return connection.connection
        sqlalchemy_engine = sqlalchemy.create_engine('postgresql://',
                                                     creator=get_dj_conn,
                                                     poolclass=NonClosingPool,
                                                     pool_reset_on_return=False)
    sa_connection = sqlalchemy_engine.connect()
    sa_connection.execution_options(autocommit=False)
    return sa_connection 
Example #19
Source File: __init__.py    From django-dbconn-retry with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_posthook(self) -> None:
        cb = Mock(name='post_reconnect_hook')
        ddr.pre_reconnect.connect(fix_connection)
        ddr.post_reconnect.connect(cb)
        from django.db import connection
        connection.close()
        connection.s_connect = connection.connect
        connection.connect = Mock(side_effect=OperationalError('reconnect testing'))
        connection.ensure_connection()
        ReconnectTests.cls_atomics['default'] = transaction.atomic(using='default')
        ReconnectTests.cls_atomics['default'].__enter__()
        self.assertTrue(cb.called)
        self.assertTrue(connection.is_usable()) 
Example #20
Source File: __init__.py    From django-dbconn-retry with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_prehook(self) -> None:
        cb = Mock(name='pre_reconnect_hook')
        ddr.pre_reconnect.connect(fix_connection)
        ddr.pre_reconnect.connect(cb)
        from django.db import connection
        connection.close()
        connection.s_connect = connection.connect
        connection.connect = Mock(side_effect=OperationalError('reconnect testing'))
        connection.ensure_connection()
        ReconnectTests.cls_atomics['default'] = transaction.atomic(using='default')
        ReconnectTests.cls_atomics['default'].__enter__()
        self.assertTrue(cb.called)
        self.assertTrue(connection.is_usable()) 
Example #21
Source File: __init__.py    From django-dbconn-retry with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_posthook(self) -> None:
        cb = Mock(name='post_reconnect_hook')
        ddr.post_reconnect.connect(cb)
        self.assertRaises(OperationalError, connection.ensure_connection)
        self.assertTrue(cb.called)
        del connection._connection_retries 
Example #22
Source File: manager.py    From scale with Apache License 2.0 4 votes vote down vote up
def _generate_database_status(self):
        """Generates the database status message

        :return: JSON describing the database status
        :rtype: dict
        """
        try:
            connection.ensure_connection()
            status_dict = {'OK': True, 'detail': {'msg': 'Database alive and well'}, 'errors': [], 'warnings': []}
        except Exception as ex:
            status_dict = {'OK': False, 'detail': {'msg': 'Unable to connect to database'}, 'errors': [{'OPERATIONAL_ERROR': 'Database unavailable.'}], 'warnings': []}
        
        return status_dict