當前位置: 首頁>>代碼示例>>Python>>正文


Python settings.DATABASES屬性代碼示例

本文整理匯總了Python中django.conf.settings.DATABASES屬性的典型用法代碼示例。如果您正苦於以下問題:Python settings.DATABASES屬性的具體用法?Python settings.DATABASES怎麽用?Python settings.DATABASES使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在django.conf.settings的用法示例。


在下文中一共展示了settings.DATABASES屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: settings_info

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import DATABASES [as 別名]
def settings_info():
    info = []
    info.append(('Deploy mode', settings.DEPLOY_MODE))
    info.append(('Database engine', settings.DATABASES['default']['ENGINE']))
    info.append(('Authentication Backends', settings.AUTHENTICATION_BACKENDS))
    info.append(('Cache backend', settings.CACHES['default']['BACKEND']))
    info.append(('Haystack engine', settings.HAYSTACK_CONNECTIONS['default']['ENGINE']))
    info.append(('Email backend', settings.EMAIL_BACKEND))
    if hasattr(settings, 'CELERY_EMAIL') and settings.CELERY_EMAIL:
        info.append(('Celery email backend', settings.CELERY_EMAIL_BACKEND))
    if hasattr(settings, 'CELERY_BROKER_URL'):
        info.append(('Celery broker', settings.CELERY_BROKER_URL.split(':')[0]))

    DATABASES = copy.deepcopy(settings.DATABASES)
    for d in DATABASES:
        if 'PASSWORD' in DATABASES[d]:
            DATABASES[d]['PASSWORD'] = '*****'
    info.append(('DATABASES',  mark_safe('<pre>'+escape(pprint.pformat(DATABASES))+'</pre>')))

    return info 
開發者ID:sfu-fas,項目名稱:coursys,代碼行數:22,代碼來源:panel.py

示例2: sqlite_check

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import DATABASES [as 別名]
def sqlite_check(app_configs, **kwargs):
    errors = []
    if 'sqlite' not in settings.DATABASES['default']['ENGINE']:
        # not using sqlite, so don't worry
        return errors

    import sqlite3
    if sqlite3.sqlite_version_info < (3, 12):
        errors.append(
            Warning(
                'SQLite version problem',
                hint='A bug is sqlite version 3.11.x causes a segfault in our tests. Upgrading to >=3.14 is suggested. This is only a warning because many things still work. Just not the tests.',
                id='coredata.E001',
            )
        )
    return errors 
開發者ID:sfu-fas,項目名稱:coursys,代碼行數:18,代碼來源:apps.py

示例3: pytest_configure

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import DATABASES [as 別名]
def pytest_configure(config):
    from django.conf import settings

    # This is already supposed to be the case by default, and we even tried
    # setting it explicitly anyway.
    #
    # But somehow, at the very beginning of the test suite (when running the
    # migrations or when the post_migrate signal is fired), the transient
    # database is on the filesystem (the value of NAME).
    #
    # We can't figure out why that is, it might be a bug in pytest-django, or
    # worse in django itself.
    #
    # Somehow the default database is always in memory, though.
    settings.DATABASES['transient']['TEST_NAME'] = ':memory:'

    # The documentation says not to use the ManifestStaticFilesStorage for
    # tests, and indeed if we do they fail.
    settings.STATICFILES_STORAGE = (
        'django.contrib.staticfiles.storage.StaticFilesStorage') 
開發者ID:ideascube,項目名稱:ideascube,代碼行數:22,代碼來源:conftest.py

示例4: destroy_test_db

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import DATABASES [as 別名]
def destroy_test_db(self, old_database_name, verbosity=1, keepdb=False):
        """
        Destroy a test database, prompting the user for confirmation if the
        database already exists.
        """
        self.connection.close()
        test_database_name = self.connection.settings_dict['NAME']
        if verbosity >= 1:
            test_db_repr = ''
            action = 'Destroying'
            if verbosity >= 2:
                test_db_repr = " ('%s')" % test_database_name
            if keepdb:
                action = 'Preserving'
            print("%s test database for alias '%s'%s..." % (
                action, self.connection.alias, test_db_repr))

        # if we want to preserve the database
        # skip the actual destroying piece.
        if not keepdb:
            self._destroy_test_db(test_database_name, verbosity)

        # Restore the original database name
        settings.DATABASES[self.connection.alias]["NAME"] = old_database_name
        self.connection.settings_dict["NAME"] = old_database_name 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:27,代碼來源:creation.py

示例5: _nodb_connection

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import DATABASES [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

示例6: run

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import DATABASES [as 別名]
def run(self):
        for db_alias in settings.DATABASES:
            self.db_alias = db_alias
            self.db_vendor = connections[self.db_alias].vendor
            print('Benchmarking %s…' % self.db_vendor)
            for cache_alias in settings.CACHES:
                cache = caches[cache_alias]
                self.cache_name = cache.__class__.__name__[:-5].lower()
                with override_settings(CACHALOT_CACHE=cache_alias):
                    self.execute_benchmark()

        self.df = pd.DataFrame.from_records(self.data)
        if not os.path.exists(RESULTS_PATH):
            os.mkdir(RESULTS_PATH)
        self.df.to_csv(os.path.join(RESULTS_PATH, 'data.csv'))

        self.xlim = (0, self.df['time'].max() * 1.01)
        self.output('db')
        self.output('cache') 
開發者ID:noripyt,項目名稱:django-cachalot,代碼行數:21,代碼來源:benchmark.py

示例7: collect_invalidations

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import DATABASES [as 別名]
def collect_invalidations(self):
        models = apps.get_models()
        data = defaultdict(list)
        cache = cachalot_caches.get_cache()
        for db_alias in settings.DATABASES:
            get_table_cache_key = cachalot_settings.CACHALOT_TABLE_KEYGEN
            model_cache_keys = {
                get_table_cache_key(db_alias, model._meta.db_table): model
                for model in models}
            for cache_key, timestamp in cache.get_many(
                    model_cache_keys.keys()).items():
                invalidation = datetime.fromtimestamp(timestamp)
                model = model_cache_keys[cache_key]
                data[db_alias].append(
                    (model._meta.app_label, model.__name__, invalidation))
                if self.last_invalidation is None \
                        or invalidation > self.last_invalidation:
                    self.last_invalidation = invalidation
            data[db_alias].sort(key=lambda row: row[2], reverse=True)
        self.record_stats({'invalidations_per_db': data.items()}) 
開發者ID:noripyt,項目名稱:django-cachalot,代碼行數:22,代碼來源:panels.py

示例8: _switch_to_test_user

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import DATABASES [as 別名]
def _switch_to_test_user(self, parameters):
        """
        Switch to the user that's used for creating the test database.

        Oracle doesn't have the concept of separate databases under the same
        user, so a separate user is used; see _create_test_db(). The main user
        is also needed for cleanup when testing is completed, so save its
        credentials in the SAVED_USER/SAVED_PASSWORD key in the settings dict.
        """
        real_settings = settings.DATABASES[self.connection.alias]
        real_settings['SAVED_USER'] = self.connection.settings_dict['SAVED_USER'] = \
            self.connection.settings_dict['USER']
        real_settings['SAVED_PASSWORD'] = self.connection.settings_dict['SAVED_PASSWORD'] = \
            self.connection.settings_dict['PASSWORD']
        real_test_settings = real_settings['TEST']
        test_settings = self.connection.settings_dict['TEST']
        real_test_settings['USER'] = real_settings['USER'] = test_settings['USER'] = \
            self.connection.settings_dict['USER'] = parameters['user']
        real_settings['PASSWORD'] = self.connection.settings_dict['PASSWORD'] = parameters['password'] 
開發者ID:reBiocoder,項目名稱:bioforum,代碼行數:21,代碼來源:creation.py

示例9: get_connection_params

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import DATABASES [as 別名]
def get_connection_params(self):
        settings_dict = self.settings_dict
        # None may be used to connect to the default 'postgres' db
        if settings_dict['NAME'] == '':
            raise ImproperlyConfigured(
                "settings.DATABASES is improperly configured. "
                "Please supply the NAME value.")
        conn_params = {
            'database': settings_dict['NAME'] or 'postgres',
        }
        conn_params.update(settings_dict['OPTIONS'])
        conn_params.pop('isolation_level', None)
        if settings_dict['USER']:
            conn_params['user'] = settings_dict['USER']
        if settings_dict['PASSWORD']:
            conn_params['password'] = settings_dict['PASSWORD']
        if settings_dict['HOST']:
            conn_params['host'] = settings_dict['HOST']
        if settings_dict['PORT']:
            conn_params['port'] = settings_dict['PORT']
        return conn_params 
開發者ID:reBiocoder,項目名稱:bioforum,代碼行數:23,代碼來源:base.py

示例10: _nodb_connection

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import DATABASES [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

示例11: count_approx

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import DATABASES [as 別名]
def count_approx(cls):
        """
        Get the approximate number of tweets.
        Executes quickly, even on large InnoDB tables.
        """
        if django_settings.DATABASES['default']['ENGINE'].endswith('mysql'):
            query = "SHOW TABLE STATUS WHERE Name = %s"
            cursor = connection.cursor()
            cursor.execute(query, [cls._meta.db_table])

            desc = cursor.description
            row = cursor.fetchone()
            row = dict(zip([col[0].lower() for col in desc], row))

            return int(row['rows'])
        else:
            return cls.objects.count() 
開發者ID:michaelbrooks,項目名稱:django-twitter-stream,代碼行數:19,代碼來源:models.py

示例12: handle

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import DATABASES [as 別名]
def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('Starting to drop DB..'))

        dbname = settings.DATABASES['default']['NAME']
        user = settings.DATABASES['default']['USER']
        password = settings.DATABASES['default']['PASSWORD']
        host = settings.DATABASES['default']['HOST']

        self.stdout.write(self.style.SUCCESS('Connecting to host..'))
        con = connect(dbname='postgres', user=user, host=host, password=password)
        con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)

        self.stdout.write(self.style.SUCCESS("Dropping database '{}'".format(dbname)))
        cur = con.cursor()
        cur.execute('DROP DATABASE ' + dbname)
        cur.close()

        con.close()

        self.stdout.write(self.style.SUCCESS('All done!')) 
開發者ID:Miserlou,項目名稱:zappa-django-utils,代碼行數:22,代碼來源:drop_pg_db.py

示例13: handle

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import DATABASES [as 別名]
def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('Starting DB creation..'))

        dbname = settings.DATABASES['default']['NAME']
        user = settings.DATABASES['default']['USER']
        password = settings.DATABASES['default']['PASSWORD']
        host = settings.DATABASES['default']['HOST']

        self.stdout.write(self.style.SUCCESS('Connecting to host..'))
        con = connect(dbname='postgres', user=user, host=host, password=password)
        con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)

        self.stdout.write(self.style.SUCCESS('Creating database'))
        cur = con.cursor()
        cur.execute('CREATE DATABASE ' + dbname)
        cur.close()

        con.close()

        self.stdout.write(self.style.SUCCESS('All done!')) 
開發者ID:Miserlou,項目名稱:zappa-django-utils,代碼行數:22,代碼來源:create_pg_db.py

示例14: handle

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import DATABASES [as 別名]
def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('Starting db creation'))

        dbname = options.get('db_name') or settings.DATABASES['default']['NAME']
        user = options.get('user') or settings.DATABASES['default']['USER']
        password = options.get('password') or settings.DATABASES['default']['PASSWORD']
        host = settings.DATABASES['default']['HOST']

        con = db.connect(user=user, host=host, password=password)
        cur = con.cursor()
        cur.execute(f'CREATE DATABASE {dbname}')
        cur.execute(f'ALTER DATABASE `{dbname}` CHARACTER SET utf8')
        cur.close()
        con.close()

        self.stdout.write(self.style.SUCCESS('All Done')) 
開發者ID:Miserlou,項目名稱:zappa-django-utils,代碼行數:18,代碼來源:create_mysql_db.py

示例15: handle

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import DATABASES [as 別名]
def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('Starting schema deletion...'))

        dbname = settings.DATABASES['default']['NAME']
        user = settings.DATABASES['default']['USER']
        password = settings.DATABASES['default']['PASSWORD']
        host = settings.DATABASES['default']['HOST']

        con = connect(dbname=dbname, user=user, host=host, password=password)

        self.stdout.write(self.style.SUCCESS('Removing schema {schema} from database {dbname}'
                                             .format(schema=settings.SCHEMA, dbname=dbname)))
        con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)

        cur = con.cursor()
        cur.execute('DROP SCHEMA {schema} CASCADE;'.format(schema=settings.SCHEMA))
        cur.close()

        con.close()

        self.stdout.write(self.style.SUCCESS('All done.')) 
開發者ID:Miserlou,項目名稱:zappa-django-utils,代碼行數:23,代碼來源:drop_pg_schema.py


注:本文中的django.conf.settings.DATABASES屬性示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。