当前位置: 首页>>代码示例>>Python>>正文


Python db.DEFAULT_DB_ALIAS属性代码示例

本文整理汇总了Python中django.db.DEFAULT_DB_ALIAS属性的典型用法代码示例。如果您正苦于以下问题:Python db.DEFAULT_DB_ALIAS属性的具体用法?Python db.DEFAULT_DB_ALIAS怎么用?Python db.DEFAULT_DB_ALIAS使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在django.db的用法示例。


在下文中一共展示了db.DEFAULT_DB_ALIAS属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: dbPop

# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import DEFAULT_DB_ALIAS [as 别名]
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']) 
开发者ID:crowdata,项目名称:crowdata,代码行数:20,代码来源:docker_setup.py

示例2: show_stats

# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import DEFAULT_DB_ALIAS [as 别名]
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)) 
开发者ID:ulule,项目名称:django-badgify,代码行数:18,代码来源:commands.py

示例3: _nodb_connection

# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import DEFAULT_DB_ALIAS [as 别名]
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 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:22,代码来源:base.py

示例4: is_nullable

# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import DEFAULT_DB_ALIAS [as 别名]
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 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:20,代码来源:query.py

示例5: add_arguments

# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import DEFAULT_DB_ALIAS [as 别名]
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) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:18,代码来源:createsuperuser.py

示例6: add_arguments

# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import DEFAULT_DB_ALIAS [as 别名]
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.') 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:26,代码来源:migrate.py

示例7: check_migrations

# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import DEFAULT_DB_ALIAS [as 别名]
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 
开发者ID:project-koku,项目名称:koku,代码行数:19,代码来源:database.py

示例8: check_migrations

# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import DEFAULT_DB_ALIAS [as 别名]
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) 
开发者ID:project-koku,项目名称:koku,代码行数:20,代码来源:sources.py

示例9: test_table_invalidated

# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import DEFAULT_DB_ALIAS [as 别名]
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) 
开发者ID:noripyt,项目名称:django-cachalot,代码行数:24,代码来源:signals.py

示例10: test_table_invalidated_multi_db

# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import DEFAULT_DB_ALIAS [as 别名]
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) 
开发者ID:noripyt,项目名称:django-cachalot,代码行数:20,代码来源:signals.py

示例11: migrator

# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import DEFAULT_DB_ALIAS [as 别名]
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) 
开发者ID:wemake-services,项目名称:django-test-migrations,代码行数:25,代码来源:pytest_plugin.py

示例12: test_signal_receiver_registered_in_test

# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import DEFAULT_DB_ALIAS [as 别名]
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,
    ) 
开发者ID:wemake-services,项目名称:django-test-migrations,代码行数:27,代码来源:test_signals.py

示例13: test_signal_receivers_added_in_tests

# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import DEFAULT_DB_ALIAS [as 别名]
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,
        ) 
开发者ID:wemake-services,项目名称:django-test-migrations,代码行数:27,代码来源:test_signals.py

示例14: _nodb_connection

# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import DEFAULT_DB_ALIAS [as 别名]
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 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:22,代码来源:base.py

示例15: is_nullable

# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import DEFAULT_DB_ALIAS [as 别名]
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 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:19,代码来源:query.py


注:本文中的django.db.DEFAULT_DB_ALIAS属性示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。