當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。