Python django.db.connections.databases() Examples

The following are 16 code examples of django.db.connections.databases(). 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.connections , or try the search function .
Example #1
Source File: utils.py    From urbanfootprint with GNU General Public License v3.0 7 votes vote down vote up
def get_client_source_data_connection():
    from footprint.client.configuration.utils import resolve_fixture
    from footprint.client.configuration.fixture import InitFixture

    source_db = resolve_fixture(None, 'init', InitFixture).import_database()

    source_db['ENGINE'] = 'django.contrib.gis.db.backends.postgis'
    source_db['OPTIONS'] = {'autocommit': True}
    source_db['NAME'] = source_db['database']
    source_db['PASSWORD'] = source_db['password']
    source_db['USER'] = source_db['user']
    source_db['HOST'] = source_db['host']
    logger.info("Connecting to database {db} on {host}".format(db=source_db['NAME'], host=source_db['HOST']))

    connections.databases['import'] = source_db

    return connections['import'] 
Example #2
Source File: router.py    From django-dynamic-db-router with MIT License 6 votes vote down vote up
def __init__(self, database, read=True, write=False):
        self.read = read
        self.write = write
        self.created_db_config = False
        if isinstance(database, str):
            self.database = database
        elif isinstance(database, dict):
            # Note: this invalidates the docs above. Update them
            # eventually.
            self.created_db_config = True
            self.unique_db_id = str(uuid4())
            connections.databases[self.unique_db_id] = database
            self.database = self.unique_db_id
        else:
            msg = ("database must be an identifier for an existing db, "
                   "or a complete configuration.")
            raise ValueError(msg) 
Example #3
Source File: test_settings.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_isolation_level_is_serializable(self):
        # Transactions *must* be SERIALIZABLE for the default connection.
        self.assertThat(
            connections.databases,
            ContainsDict(
                {
                    "default": ContainsDict(
                        {
                            "OPTIONS": ContainsDict(
                                {
                                    "isolation_level": Equals(
                                        ISOLATION_LEVEL_REPEATABLE_READ
                                    )
                                }
                            )
                        }
                    )
                }
            ),
        ) 
Example #4
Source File: tests.py    From django-dynamic-db-router with MIT License 5 votes vote down vote up
def test_cleans_up(self):
        starting_connections = len(connections.databases)
        with in_database(self.test_db_config, write=True):
            G(TestModel, name='Sue')
        ending_connections = len(connections.databases)
        self.assertEqual(starting_connections, ending_connections) 
Example #5
Source File: router.py    From django-dynamic-db-router with MIT License 5 votes vote down vote up
def __exit__(self, exc_type, exc_value, traceback):
        THREAD_LOCAL.DB_FOR_READ_OVERRIDE.pop()
        THREAD_LOCAL.DB_FOR_WRITE_OVERRIDE.pop()
        if self.created_db_config:
            connections[self.unique_db_id].close()
            del connections.databases[self.unique_db_id] 
Example #6
Source File: migrations.py    From django-prometheus with Apache License 2.0 5 votes vote down vote up
def ExportMigrations():
    """Exports counts of unapplied migrations.

    This is meant to be called during app startup, ideally by
    django_prometheus.apps.AppConfig.
    """

    # Import MigrationExecutor lazily. MigrationExecutor checks at
    # import time that the apps are ready, and they are not when
    # django_prometheus is imported. ExportMigrations() should be
    # called in AppConfig.ready(), which signals that all apps are
    # ready.
    from django.db.migrations.executor import MigrationExecutor

    if "default" in connections and (
        isinstance(connections["default"], DatabaseWrapper)
    ):
        # This is the case where DATABASES = {} in the configuration,
        # i.e. the user is not using any databases. Django "helpfully"
        # adds a dummy database and then throws when you try to
        # actually use it. So we don't do anything, because trying to
        # export stats would crash the app on startup.
        return
    for alias in connections.databases:
        executor = MigrationExecutor(connections[alias])
        ExportMigrationsForDatabase(alias, executor) 
Example #7
Source File: mocks.py    From django-mock-queries with MIT License 5 votes vote down vote up
def mock_django_connection(disabled_features=None):
    """ Overwrite the Django database configuration with a mocked version.

    This is a helper function that does the actual monkey patching.
    """
    db = connections.databases['default']
    db['PASSWORD'] = '****'
    db['USER'] = '**Database disabled for unit tests**'
    ConnectionHandler.__getitem__ = MagicMock(name='mock_connection')
    # noinspection PyUnresolvedReferences
    mock_connection = ConnectionHandler.__getitem__.return_value
    if disabled_features:
        for feature in disabled_features:
            setattr(mock_connection.features, feature, False)
    mock_ops = mock_connection.ops

    # noinspection PyUnusedLocal
    def compiler(queryset, connection, using, **kwargs):
        result = MagicMock(name='mock_connection.ops.compiler()')
        # noinspection PyProtectedMember
        result.execute_sql.side_effect = NotSupportedError(
            "Mock database tried to execute SQL for {} model.".format(
                queryset.model._meta.object_name))
        result.has_results.side_effect = result.execute_sql.side_effect
        return result

    mock_ops.compiler.return_value.side_effect = compiler
    mock_ops.integer_field_range.return_value = (-sys.maxsize - 1, sys.maxsize)
    mock_ops.max_name_length.return_value = sys.maxsize

    Model.refresh_from_db = Mock()  # Make this into a noop. 
Example #8
Source File: database.py    From zing with GNU General Public License v3.0 5 votes vote down vote up
def test_backend_db():
    """Ensure that we are always testing sqlite on fast in memory DB"""
    from django.db import connection, connections

    if connection.vendor == "sqlite":
        assert "file:memorydb" in connections.databases["default"]["NAME"] 
Example #9
Source File: tests.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_time_zone_parameter_not_supported_if_database_supports_timezone(self):
        connections.databases['tz'] = connections.databases['default'].copy()
        connections.databases['tz']['TIME_ZONE'] = 'Asia/Bangkok'
        tz_conn = connections['tz']
        try:
            with self.assertRaises(ImproperlyConfigured):
                tz_conn.cursor()
        finally:
            connections['tz'].close()       # in case the test fails
            del connections['tz']
            del connections.databases['tz'] 
Example #10
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_time_zone_parameter_not_supported_if_database_supports_timezone(self):
        connections.databases['tz'] = connections.databases['default'].copy()
        connections.databases['tz']['TIME_ZONE'] = 'Asia/Bangkok'
        tz_conn = connections['tz']
        try:
            msg = (
                "Connection 'tz' cannot set TIME_ZONE because its engine "
                "handles time zones conversions natively."
            )
            with self.assertRaisesMessage(ImproperlyConfigured, msg):
                tz_conn.cursor()
        finally:
            connections['tz'].close()       # in case the test fails
            del connections['tz']
            del connections.databases['tz'] 
Example #11
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_time_zone_parameter_not_supported_if_database_supports_timezone(self):
        connections.databases['tz'] = connections.databases['default'].copy()
        connections.databases['tz']['TIME_ZONE'] = 'Asia/Bangkok'
        tz_conn = connections['tz']
        try:
            msg = (
                "Connection 'tz' cannot set TIME_ZONE because its engine "
                "handles time zones conversions natively."
            )
            with self.assertRaisesMessage(ImproperlyConfigured, msg):
                tz_conn.cursor()
        finally:
            connections['tz'].close()       # in case the test fails
            del connections['tz']
            del connections.databases['tz'] 
Example #12
Source File: listener.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def createConnection(self):
        """Create new database connection."""
        db = connections.databases[self.alias]
        backend = load_backend(db["ENGINE"])
        return backend.DatabaseWrapper(
            db, self.alias, allow_thread_sharing=True
        ) 
Example #13
Source File: test_settings.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_atomic_requests_are_enabled(self):
        # ATOMIC_REQUESTS *must* be set for the default connection.
        self.assertThat(
            connections.databases,
            ContainsDict(
                {"default": ContainsDict({"ATOMIC_REQUESTS": Is(True)})}
            ),
        ) 
Example #14
Source File: bootresources.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def _get_new_connection(self):
        """Create new database connection."""
        db = connections.databases[self.alias]
        backend = load_backend(db["ENGINE"])
        return backend.DatabaseWrapper(db, self.alias) 
Example #15
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 4 votes vote down vote up
def get_ogr_db_string():
    """
    Construct the DB string that GDAL will use to inspect the database.
    GDAL will create its own connection to the database, so we re-use the
    connection settings from the Django test.
    """
    db = connections.databases['default']

    # Map from the django backend into the OGR driver name and database identifier
    # https://www.gdal.org/ogr/ogr_formats.html
    #
    # TODO: Support Oracle (OCI).
    drivers = {
        'django.contrib.gis.db.backends.postgis': ('PostgreSQL', "PG:dbname='%(db_name)s'", ' '),
        'django.contrib.gis.db.backends.mysql': ('MySQL', 'MYSQL:"%(db_name)s"', ','),
        'django.contrib.gis.db.backends.spatialite': ('SQLite', '%(db_name)s', '')
    }

    db_engine = db['ENGINE']
    if db_engine not in drivers:
        return None

    drv_name, db_str, param_sep = drivers[db_engine]

    # Ensure that GDAL library has driver support for the database.
    try:
        Driver(drv_name)
    except GDALException:
        return None

    # SQLite/SpatiaLite in-memory databases
    if db['NAME'] == ":memory:":
        return None

    # Build the params of the OGR database connection string
    params = [db_str % {'db_name': db['NAME']}]

    def add(key, template):
        value = db.get(key, None)
        # Don't add the parameter if it is not in django's settings
        if value:
            params.append(template % value)
    add('HOST', "host='%s'")
    add('PORT', "port='%s'")
    add('USER', "user='%s'")
    add('PASSWORD', "password='%s'")

    return param_sep.join(params) 
Example #16
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 4 votes vote down vote up
def get_ogr_db_string():
    """
    Construct the DB string that GDAL will use to inspect the database.
    GDAL will create its own connection to the database, so we re-use the
    connection settings from the Django test.
    """
    db = connections.databases['default']

    # Map from the django backend into the OGR driver name and database identifier
    # https://www.gdal.org/ogr/ogr_formats.html
    #
    # TODO: Support Oracle (OCI).
    drivers = {
        'django.contrib.gis.db.backends.postgis': ('PostgreSQL', "PG:dbname='%(db_name)s'", ' '),
        'django.contrib.gis.db.backends.mysql': ('MySQL', 'MYSQL:"%(db_name)s"', ','),
        'django.contrib.gis.db.backends.spatialite': ('SQLite', '%(db_name)s', '')
    }

    db_engine = db['ENGINE']
    if db_engine not in drivers:
        return None

    drv_name, db_str, param_sep = drivers[db_engine]

    # Ensure that GDAL library has driver support for the database.
    try:
        Driver(drv_name)
    except GDALException:
        return None

    # SQLite/SpatiaLite in-memory databases
    if db['NAME'] == ":memory:":
        return None

    # Build the params of the OGR database connection string
    params = [db_str % {'db_name': db['NAME']}]

    def add(key, template):
        value = db.get(key, None)
        # Don't add the parameter if it is not in django's settings
        if value:
            params.append(template % value)
    add('HOST', "host='%s'")
    add('PORT', "port='%s'")
    add('USER', "user='%s'")
    add('PASSWORD', "password='%s'")

    return param_sep.join(params)