Python django.db.DEFAULT_DB_ALIAS Examples

The following are 30 code examples of django.db.DEFAULT_DB_ALIAS(). 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 , or try the search function .
Example #1
Source File: query.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def is_nullable(self, field):
        """
        Check if the given field should be treated as nullable.

        Some backends treat '' as null and Django treats such fields as
        nullable for those backends. In such situations field.null can be
        False even if we should treat the field as nullable.
        """
        # We need to use DEFAULT_DB_ALIAS here, as QuerySet does not have
        # (nor should it have) knowledge of which connection is going to be
        # used. The proper fix would be to defer all decisions where
        # is_nullable() is needed to the compiler stage, but that is not easy
        # to do currently.
        return (
            connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls and
            field.empty_strings_allowed
        ) or field.null 
Example #2
Source File: base.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def _nodb_connection(self):
        nodb_connection = super(DatabaseWrapper, self)._nodb_connection
        try:
            nodb_connection.ensure_connection()
        except (DatabaseError, WrappedDatabaseError):
            warnings.warn(
                "Normally Django will use a connection to the 'postgres' database "
                "to avoid running initialization queries against the production "
                "database when it's not needed (for example, when running tests). "
                "Django was unable to create a connection to the 'postgres' database "
                "and will use the default database instead.",
                RuntimeWarning
            )
            settings_dict = self.settings_dict.copy()
            settings_dict['NAME'] = settings.DATABASES[DEFAULT_DB_ALIAS]['NAME']
            nodb_connection = self.__class__(
                self.settings_dict.copy(),
                alias=self.alias,
                allow_thread_sharing=False)
        return nodb_connection 
Example #3
Source File: commands.py    From django-badgify with MIT License 6 votes vote down vote up
def show_stats(**kwargs):
    """
    Shows badges stats.
    """
    db_read = kwargs.get('db_read', DEFAULT_DB_ALIAS)

    badges = (Badge.objects.using(db_read)
                           .all()
                           .annotate(u_count=Count('users'))
                           .order_by('u_count'))

    for badge in badges:
        logger.info('{:<20} {:>10} users awarded | users_count: {})'.format(
            badge.name,
            badge.u_count,
            badge.users_count)) 
Example #4
Source File: query.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def is_nullable(self, field):
        """
        A helper to check if the given field should be treated as nullable.

        Some backends treat '' as null and Django treats such fields as
        nullable for those backends. In such situations field.null can be
        False even if we should treat the field as nullable.
        """
        # We need to use DEFAULT_DB_ALIAS here, as QuerySet does not have
        # (nor should it have) knowledge of which connection is going to be
        # used. The proper fix would be to defer all decisions where
        # is_nullable() is needed to the compiler stage, but that is not easy
        # to do currently.
        if ((connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls)
                and field.empty_strings_allowed):
            return True
        else:
            return field.null 
Example #5
Source File: createsuperuser.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def add_arguments(self, parser):
        parser.add_argument('--%s' % self.UserModel.USERNAME_FIELD,
            dest=self.UserModel.USERNAME_FIELD, default=None,
            help='Specifies the login for the superuser.')
        parser.add_argument('--noinput', action='store_false', dest='interactive', default=True,
            help=('Tells Django to NOT prompt the user for input of any kind. '
                  'You must use --%s with --noinput, along with an option for '
                  'any other required field. Superusers created with --noinput will '
                  ' not be able to log in until they\'re given a valid password.' %
                  self.UserModel.USERNAME_FIELD))
        parser.add_argument('--database', action='store', dest='database',
                default=DEFAULT_DB_ALIAS,
                help='Specifies the database to use. Default is "default".')
        for field in self.UserModel.REQUIRED_FIELDS:
            parser.add_argument('--%s' % field, dest=field, default=None,
                help='Specifies the %s for the superuser.' % field) 
Example #6
Source File: migrate.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def add_arguments(self, parser):
        parser.add_argument('app_label', nargs='?',
            help='App label of an application to synchronize the state.')
        parser.add_argument('migration_name', nargs='?',
            help=(
                'Database state will be brought to the state after that '
                'migration. Use the name "zero" to unapply all migrations.'
            ),
        )
        parser.add_argument('--noinput', action='store_false', dest='interactive', default=True,
            help='Tells Django to NOT prompt the user for input of any kind.')
        parser.add_argument('--no-initial-data', action='store_false', dest='load_initial_data', default=True,
            help='Tells Django not to load any initial data after database synchronization.')
        parser.add_argument('--database', action='store', dest='database',
            default=DEFAULT_DB_ALIAS, help='Nominates a database to synchronize. '
                'Defaults to the "default" database.')
        parser.add_argument('--fake', action='store_true', dest='fake', default=False,
            help='Mark migrations as run without actually running them.')
        parser.add_argument('--fake-initial', action='store_true', dest='fake_initial', default=False,
            help='Detect if tables already exist and fake-apply initial migrations if so. Make sure '
                 'that the current database schema matches your initial migration before using this '
                 'flag. Django will only check for an existing table name.')
        parser.add_argument('--list', '-l', action='store_true', dest='list', default=False,
            help='Show a list of all known migrations and which are applied.') 
Example #7
Source File: database.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def check_migrations():
    """
    Check the status of database migrations.
    The koku API server is responsible for running all database migrations.  This method
    will return the state of the database and whether or not all migrations have been completed.
    Hat tip to the Stack Overflow contributor: https://stackoverflow.com/a/31847406
    Returns:
        Boolean - True if database is available and migrations have completed.  False otherwise.
    """
    try:
        connection = connections[DEFAULT_DB_ALIAS]
        connection.prepare_database()
        executor = MigrationExecutor(connection)
        targets = executor.loader.graph.leaf_nodes()
        return not executor.migration_plan(targets)
    except OperationalError:
        return False 
Example #8
Source File: sources.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def check_migrations(self):
        """
        Check the status of database migrations.

        The koku API server is responsible for running all database migrations.  This method
        will return the state of the database and whether or not all migrations have been completed.

        Hat tip to the Stack Overflow contributor: https://stackoverflow.com/a/31847406

        Returns:
            Boolean - True if database is available and migrations have completed.  False otherwise.

        """
        connection = connections[DEFAULT_DB_ALIAS]
        connection.prepare_database()
        executor = MigrationExecutor(connection)
        targets = executor.loader.graph.leaf_nodes()
        return not executor.migration_plan(targets) 
Example #9
Source File: signals.py    From django-cachalot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_table_invalidated_multi_db(self):
        db_alias2 = next(alias for alias in settings.DATABASES
                         if alias != DEFAULT_DB_ALIAS)
        l = []

        def receiver(sender, **kwargs):
            db_alias = kwargs['db_alias']
            l.append((sender, db_alias))

        post_invalidation.connect(receiver)
        self.assertListEqual(l, [])
        Test.objects.using(DEFAULT_DB_ALIAS).create(name='test')
        self.assertListEqual(l, [('cachalot_test', DEFAULT_DB_ALIAS)])
        Test.objects.using(db_alias2).create(name='test')
        self.assertListEqual(l, [
            ('cachalot_test', DEFAULT_DB_ALIAS),
            ('cachalot_test', db_alias2)])
        post_invalidation.disconnect(receiver) 
Example #10
Source File: pytest_plugin.py    From django-test-migrations with MIT License 6 votes vote down vote up
def migrator(_mute_migration_signals, migrator_factory):  # noqa: WPS442
    """
    Useful alias for ``'default'`` database in ``django``.

    That's a predefined instance of a ``migrator_factory``.

    How to use it? Here's an example.

    .. code:: python

        @pytest.mark.django_db
        def test_migration(migrator):
            old_state = migrator.apply_initial_migration(('main_app', None))
            new_state = migrator.apply_tested_migration(
                ('main_app', '0001_initial'),
            )

            assert isinstance(old_state, ProjectState)
            assert isinstance(new_state, ProjectState)

    Just one step easier than ``migrator_factory`` fixture.
    """
    return migrator_factory(DEFAULT_DB_ALIAS) 
Example #11
Source File: test_signals.py    From django-test-migrations with MIT License 6 votes vote down vote up
def test_signal_receiver_registered_in_test(mocker, signal):
    """Ensure migration signal receivers registered in tests are called."""
    signal_receiver_mock = mocker.MagicMock()
    main_app_config = apps.get_app_config('main_app')
    signal.connect(
        signal_receiver_mock,
        sender=main_app_config,
        dispatch_uid=DISPATCH_UID,
    )
    verbosity = 0
    interactive = False
    # call `migrate` management command to trigger ``pre_migrate`` and
    # ``post_migrate`` signals
    call_command('migrate', verbosity=verbosity, interactive=interactive)

    signal_receiver_mock.assert_called_once_with(
        sender=main_app_config,
        app_config=main_app_config,
        apps=mocker.ANY,  # we don't have any reference to this object
        using=DEFAULT_DB_ALIAS,
        verbosity=verbosity,
        interactive=interactive,
        plan=mocker.ANY,  # not important for this test
        signal=signal,
    ) 
Example #12
Source File: test_signals.py    From django-test-migrations with MIT License 6 votes vote down vote up
def test_signal_receivers_added_in_tests(self):
        """Ensure migration signals receivers connected in tests are called."""
        verbosity = 0
        interactive = False
        # call `migrate` management command to trigger ``pre_migrate`` and
        # ``post_migrate`` signals
        call_command('migrate', verbosity=verbosity, interactive=interactive)

        common_kwargs = {
            'sender': self.main_app_config,
            'app_config': self.main_app_config,
            'apps': mock.ANY,  # we don't have any reference to this object
            'using': DEFAULT_DB_ALIAS,
            'verbosity': verbosity,
            'interactive': interactive,
            'plan': mock.ANY,  # not important for this test
        }
        self.pre_migrate_receiver_mock.assert_called_once_with(
            **common_kwargs,
            signal=pre_migrate,
        )
        self.post_migrate_receiver_mock.assert_called_once_with(
            **common_kwargs,
            signal=post_migrate,
        ) 
Example #13
Source File: base.py    From bioforum with MIT License 6 votes vote down vote up
def _nodb_connection(self):
        nodb_connection = super()._nodb_connection
        try:
            nodb_connection.ensure_connection()
        except (Database.DatabaseError, WrappedDatabaseError):
            warnings.warn(
                "Normally Django will use a connection to the 'postgres' database "
                "to avoid running initialization queries against the production "
                "database when it's not needed (for example, when running tests). "
                "Django was unable to create a connection to the 'postgres' database "
                "and will use the default database instead.",
                RuntimeWarning
            )
            settings_dict = self.settings_dict.copy()
            settings_dict['NAME'] = settings.DATABASES[DEFAULT_DB_ALIAS]['NAME']
            nodb_connection = self.__class__(
                self.settings_dict.copy(),
                alias=self.alias,
                allow_thread_sharing=False)
        return nodb_connection 
Example #14
Source File: query.py    From bioforum with MIT License 6 votes vote down vote up
def is_nullable(self, field):
        """
        Check if the given field should be treated as nullable.

        Some backends treat '' as null and Django treats such fields as
        nullable for those backends. In such situations field.null can be
        False even if we should treat the field as nullable.
        """
        # We need to use DEFAULT_DB_ALIAS here, as QuerySet does not have
        # (nor should it have) knowledge of which connection is going to be
        # used. The proper fix would be to defer all decisions where
        # is_nullable() is needed to the compiler stage, but that is not easy
        # to do currently.
        if connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls and field.empty_strings_allowed:
            return True
        else:
            return field.null 
Example #15
Source File: docker_setup.py    From crowdata with MIT License 6 votes vote down vote up
def dbPop():
	for directive in ["USER", "EMAIL", "PASSWORD", "WITH_DB"]:
		if "crowdata_%s" % directive not in os.environ.keys():
			os.environ['crowdata_%s' % directive] = defaults[directive]

	if os.environ['crowdata_WITH_DB'] is not None:
		print "Populating database from backup %s" % os.environ['crowdata_WITH_DB']
		import subprocess

		subprocess.call(("pg_restore --dbname=%s --verbose %s --clean" % (os.environ['crowdata_NAME'], os.environ['crowdata_WITH_DB'])).split(" "))

	# superuser
	print "Creating superuser"
	from django.db import DEFAULT_DB_ALIAS as database
	from django.contrib.auth.models import User

	User.objects.db_manager(database).create_superuser(
		os.environ['crowdata_USER'], os.environ['crowdata_EMAIL'], os.environ['crowdata_PASSWORD']) 
Example #16
Source File: signals.py    From django-cachalot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_table_invalidated(self):
        l = []

        def receiver(sender, **kwargs):
            db_alias = kwargs['db_alias']
            l.append((sender, db_alias))

        post_invalidation.connect(receiver)
        self.assertListEqual(l, [])
        list(Test.objects.all())
        self.assertListEqual(l, [])
        Test.objects.create(name='test1')
        self.assertListEqual(l, [('cachalot_test', DEFAULT_DB_ALIAS)])
        post_invalidation.disconnect(receiver)

        del l[:]  # Empties the list
        post_invalidation.connect(receiver, sender=User._meta.db_table)
        Test.objects.create(name='test2')
        self.assertListEqual(l, [])
        User.objects.create_user('user')
        self.assertListEqual(l, [('auth_user', DEFAULT_DB_ALIAS)])
        post_invalidation.disconnect(receiver, sender=User._meta.db_table) 
Example #17
Source File: query.py    From bioforum with MIT License 5 votes vote down vote up
def sql_with_params(self):
        """
        Return the query as an SQL string and the parameters that will be
        substituted into the query.
        """
        return self.get_compiler(DEFAULT_DB_ALIAS).as_sql() 
Example #18
Source File: test_api.py    From resolwe with Apache License 2.0 5 votes vote down vote up
def test_prefetch(self):
        descriptor_schema_1 = DescriptorSchema.objects.create(
            contributor=self.contributor,
        )
        descriptor_schema_2 = DescriptorSchema.objects.create(contributor=self.user,)

        for _ in range(5):
            collection = Collection.objects.create(
                contributor=self.contributor, descriptor_schema=descriptor_schema_1
            )
            assign_perm("view_collection", self.contributor, collection)

        for _ in range(5):
            collection = Collection.objects.create(
                contributor=self.user, descriptor_schema=descriptor_schema_2
            )
            assign_perm("view_collection", self.contributor, collection)

        request = factory.get("/", "", format="json")
        force_authenticate(request, self.contributor)

        conn = connections[DEFAULT_DB_ALIAS]
        with CaptureQueriesContext(conn) as captured_queries:
            response = self.collection_list_viewset(request)
            self.assertEqual(len(response.data), 10)
            self.assertEqual(len(captured_queries), 60) 
Example #19
Source File: utils.py    From django-cassandra-engine with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_cql_models(app, connection=None, keyspace=None):
    """
    :param app: django models module
    :param connection: connection name
    :param keyspace: keyspace
    :return: list of all cassandra.cqlengine.Model within app that should be
    synced to keyspace.
    """
    from .models import DjangoCassandraModel

    models = []
    single_cassandra_connection = len(list(get_cassandra_connections())) == 1
    is_default_connection = (
        connection == DEFAULT_DB_ALIAS or single_cassandra_connection
    )

    for name, obj in inspect.getmembers(app):
        cql_model_types = (cqlengine.models.Model, DjangoCassandraModel)
        if (
            inspect.isclass(obj)
            and issubclass(obj, cql_model_types)
            and not obj.__abstract__
        ):
            if (
                obj.__connection__ == connection
                or (obj.__connection__ is None and is_default_connection)
                or obj.__connection__ is None
                and obj.__keyspace__ is not None
                and obj.__keyspace__ == keyspace
            ):
                models.append(obj)

    return models 
Example #20
Source File: testcases.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def assertNumQueries(self, num, func=None, *args, **kwargs):
        using = kwargs.pop("using", DEFAULT_DB_ALIAS)
        conn = connections[using]

        context = _AssertNumQueriesContext(self, num, conn)
        if func is None:
            return context

        with context:
            func(*args, **kwargs) 
Example #21
Source File: test_relations.py    From resolwe with Apache License 2.0 5 votes vote down vote up
def test_prefetch(self):
        self.relation_group.delete()
        self.relation_series.delete()

        descriptor_schema_1 = DescriptorSchema.objects.create(
            contributor=self.contributor,
        )
        descriptor_schema_2 = DescriptorSchema.objects.create(contributor=self.user,)

        self.collection.descriptor_schema = descriptor_schema_1
        self.collection.save()

        self.collection_2.contributor = self.user
        self.collection_2.descriptor_schema = descriptor_schema_2
        self.collection_2.save()

        for i in range(5):
            relation = Relation.objects.create(
                contributor=self.contributor,
                type=self.rel_type_group,
                category="replicates-{}".format(i),
                collection=self.collection,
            )
            assign_perm("view_relation", self.contributor, relation)

        for i in range(5):
            relation = Relation.objects.create(
                contributor=self.user,
                type=self.rel_type_group,
                category="replicates-{}".format(i),
                collection=self.collection_2,
            )
            assign_perm("view_relation", self.contributor, relation)

        conn = connections[DEFAULT_DB_ALIAS]
        with CaptureQueriesContext(conn) as captured_queries:
            response = self._get_list(self.contributor)
            self.assertEqual(len(response.data), 10)
            self.assertEqual(len(captured_queries), 12) 
Example #22
Source File: plan.py    From django-test-migrations with MIT License 5 votes vote down vote up
def all_migrations(
    database: str = DEFAULT_DB_ALIAS,
    app_names: Optional[List[str]] = None,
) -> List[Node]:
    """
    Returns the sorted list of migrations nodes.

    The order is the same as when migrations are applied.

    When you might need this function?
    When you are testing the migration order.

    For example, imagine that you have a direct dependency:
    ``main_app.0002_migration`` and ``other_app.0001_initial``
    where ``other_app.0001_initial`` relies on the model or field
    introduced in ``main_app.0002_migration``.

    You can use ``dependencies`` field
    to ensure that everything works correctly.

    But, sometimes migrations are squashed,
    sometimes they are renamed, refactored, and moved.

    It would be better to have a test that will ensure
    that ``other_app.0001_initial`` comes after ``main_app.0002_migration``.
    And everything works as expected.
    """
    loader = MigrationLoader(connections[database])

    if app_names:
        _validate_app_names(app_names)
        targets = [
            key
            for key in loader.graph.leaf_nodes()
            if key[0] in app_names
        ]
    else:
        targets = loader.graph.leaf_nodes()
    return _generate_plan(targets, loader) 
Example #23
Source File: test_api.py    From resolwe with Apache License 2.0 5 votes vote down vote up
def test_prefetch(self):
        self.entity.delete()

        descriptor_schema_2 = DescriptorSchema.objects.create(contributor=self.user)
        collection_2 = Collection.objects.create(
            contributor=self.user, descriptor_schema=descriptor_schema_2
        )

        for i in range(5):
            create_kwargs = {
                "contributor": self.contributor,
                "descriptor_schema": self.descriptor_schema,
            }
            if i < 4:
                create_kwargs["collection"] = self.collection
            entity = Entity.objects.create(**create_kwargs)
            assign_perm("view_entity", self.contributor, entity)

        for i in range(5):
            create_kwargs = {
                "contributor": self.user,
                "descriptor_schema": descriptor_schema_2,
            }
            if i < 4:
                create_kwargs["collection"] = collection_2
            entity = Entity.objects.create(**create_kwargs)
            assign_perm("view_entity", self.contributor, entity)

        request = factory.get("/", "", format="json")
        force_authenticate(request, self.contributor)

        conn = connections[DEFAULT_DB_ALIAS]
        with CaptureQueriesContext(conn) as captured_queries:
            response = self.entity_list_viewset(request)
            self.assertEqual(len(response.data), 10)
            self.assertEqual(len(captured_queries), 63) 
Example #24
Source File: testcase.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def _databases(cls):
        if getattr(cls, 'multi_db', False):
            return connections
        else:
            return [DEFAULT_DB_ALIAS] 
Example #25
Source File: testcases.py    From bioforum with MIT License 5 votes vote down vote up
def _databases_names(cls, include_mirrors=True):
        # If the test case has a multi_db=True flag, act on all databases,
        # including mirrors or not. Otherwise, just on the default DB.
        if cls.multi_db:
            return [
                alias for alias in connections
                if include_mirrors or not connections[alias].settings_dict['TEST']['MIRROR']
            ]
        else:
            return [DEFAULT_DB_ALIAS] 
Example #26
Source File: testcases.py    From bioforum with MIT License 5 votes vote down vote up
def assertNumQueries(self, num, func=None, *args, using=DEFAULT_DB_ALIAS, **kwargs):
        conn = connections[using]

        context = _AssertNumQueriesContext(self, num, conn)
        if func is None:
            return context

        with context:
            func(*args, **kwargs) 
Example #27
Source File: createsuperuser.py    From bioforum with MIT License 5 votes vote down vote up
def add_arguments(self, parser):
        parser.add_argument(
            '--%s' % self.UserModel.USERNAME_FIELD,
            dest=self.UserModel.USERNAME_FIELD, default=None,
            help='Specifies the login for the superuser.',
        )
        parser.add_argument(
            '--noinput', '--no-input', action='store_false', dest='interactive',
            help=(
                'Tells Django to NOT prompt the user for input of any kind. '
                'You must use --%s with --noinput, along with an option for '
                'any other required field. Superusers created with --noinput will '
                'not be able to log in until they\'re given a valid password.' %
                self.UserModel.USERNAME_FIELD
            ),
        )
        parser.add_argument(
            '--database', action='store', dest='database',
            default=DEFAULT_DB_ALIAS,
            help='Specifies the database to use. Default is "default".',
        )
        for field in self.UserModel.REQUIRED_FIELDS:
            parser.add_argument(
                '--%s' % field, dest=field, default=None,
                help='Specifies the %s for the superuser.' % field,
            ) 
Example #28
Source File: changepassword.py    From bioforum with MIT License 5 votes vote down vote up
def add_arguments(self, parser):
        parser.add_argument(
            'username', nargs='?',
            help='Username to change password for; by default, it\'s the current username.',
        )
        parser.add_argument(
            '--database', action='store', dest='database',
            default=DEFAULT_DB_ALIAS,
            help='Specifies the database to use. Default is "default".',
        ) 
Example #29
Source File: views.py    From bioforum with MIT License 5 votes vote down vote up
def kmz(request, label, model, field_name=None, using=DEFAULT_DB_ALIAS):
    """
    Return KMZ for the given app label, model, and field name.
    """
    return kml(request, label, model, field_name, compress=True, using=using) 
Example #30
Source File: query.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def sql_with_params(self):
        """
        Return the query as an SQL string and the parameters that will be
        substituted into the query.
        """
        return self.get_compiler(DEFAULT_DB_ALIAS).as_sql()