Here are the examples of the python api django.conf.settings.DATABASES taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
157 Examples
3
Example 1
Project: django-sqlserver Source File: tests.py
def setUp(self):
transaction.enter_transaction_management()
self.person = Person.objects.create(name='Reinhardt')
# We have to commit here so that code in run_select_for_update can
# see this data.
transaction.commit()
# We need another database connection to test that one connection
# issuing a SELECT ... FOR UPDATE will block.
new_connections = ConnectionHandler(settings.DATABASES)
self.new_connection = new_connections[DEFAULT_DB_ALIAS]
self.new_connection.enter_transaction_management()
# We need to set settings.DEBUG to True so we can capture
# the output SQL to examine.
self._old_debug = settings.DEBUG
settings.DEBUG = True
3
Example 2
@classmethod
def _use_read_replica(cls, queryset):
"""
If there's a read replica that can be used, return a cursor to that.
Otherwise, return a cursor to the regular database.
Args:
queryset (QuerySet): The queryset that we would like to use the read replica for.
Returns:
QuerySet
"""
return (
queryset.using("read_replica")
if "read_replica" in settings.DATABASES
else queryset
)
3
Example 3
def setUp(self):
self.t1 = Test.objects.create(name='test1')
self.t2 = Test.objects.create(name='test2')
self.db_alias2 = next(alias for alias in settings.DATABASES
if alias != DEFAULT_DB_ALIAS)
connection2 = connections[self.db_alias2]
self.is_sqlite2 = connection2.vendor == 'sqlite'
self.is_mysql2 = connection2.vendor == 'mysql'
if self.is_mysql2:
# We need to reopen the connection or Django
# will execute an extra SQL request below.
connection2.cursor()
3
Example 4
def setUp(self):
# Create a second connection to the default database
new_connections = ConnectionHandler(settings.DATABASES)
self.conn2 = new_connections[DEFAULT_DB_ALIAS]
# Put both DB connections into managed transaction mode
transaction.enter_transaction_management()
self.conn2.enter_transaction_management()
3
Example 5
@classmethod
def reload_settings(cls):
"""Reload settings into connection handler
(django.db.utils.ConnectionHandler)
"""
if cls.DB_ALIAS in connections._connections:
del connections._connections[cls.DB_ALIAS]
connections.databases = settings.DATABASES
3
Example 6
def handle(self, *args, **options):
database = options.get('database', 'default')
if (settings.DATABASES[database]['ENGINE'] == 'tenant_schemas.postgresql_backend' or
MigrateCommand is BaseCommand):
raise CommandError("migrate has been disabled, for database '{0}'. Use migrate_schemas "
"instead. Please read the docuementation if you don't know why you "
"shouldn't call migrate directly!".format(database))
super(Command, self).handle(*args, **options)
3
Example 7
Project: django-dbindexer Source File: base.py
def DatabaseWrapper(settings_dict, *args, **kwargs):
target_settings = settings_dict['TARGET']
if isinstance(target_settings, (str, unicode)):
target_settings = settings.DATABASES[target_settings]
engine = target_settings['ENGINE'] + '.base'
target = import_module(engine).DatabaseWrapper
class Wrapper(BaseDatabaseWrapper, target):
pass
# Update settings with target database settings (which can contain nested dicts).
merged_settings = settings_dict.copy()
merge_dicts(merged_settings, target_settings)
return Wrapper(merged_settings, *args, **kwargs)
3
Example 8
def count(self):
postgres_engines = ("postgis", "postgresql", "django_postgrespool")
engine = settings.DATABASES[self.db]["ENGINE"].split(".")[-1]
is_postgres = engine.startswith(postgres_engines)
# In Django 1.9 the query.having property was removed and the
# query.where property will be truthy if either where or having
# clauses are present. In earlier versions these were two separate
# properties query.where and query.having
if DJANGO_VERSION_GTE_19:
is_filtered = self.query.where
else:
is_filtered = self.query.where or self.query.having
if not is_postgres or is_filtered:
return super(FuzzyCountQuerySet, self).count()
cursor = connections[self.db].cursor()
cursor.execute("SELECT reltuples FROM pg_class "
"WHERE relname = '%s';" % self.model._meta.db_table)
return int(cursor.fetchone()[0])
3
Example 9
@unittest.skipIf(settings.DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3', 'Case Sensitive __contains queries are not supported on sqlite.')
def test_case_sensitive(self):
# TODO: make this test run on travis with postgres/mysql to be sure
# this functionality actually works.
class TheSearchForm(SearchForm):
SEARCH_FIELDS = ('field_a', 'field_c')
CASE_SENSITIVE = True
model = ChangeListModel
self.assertTrue(TheSearchForm.CASE_SENSITIVE)
upper_cased = ChangeListModel.objects.create(field_a='TeSt')
lower_cased = ChangeListModel.objects.create(field_a='test')
form = TheSearchForm({'q': 'TeSt'})
form.full_clean()
self.assertIn(upper_cased, form.get_queryset())
self.assertNotIn(lower_cased, form.get_queryset())
3
Example 10
def test_sql_mapping(test_field_name, db_name='default'):
engine = settings.DATABASES[db_name]['ENGINE'].split('.')[-1]
sql_for_engine = __import__('django_evolution.tests.db.%s' % (engine),
{}, {}, [''])
return getattr(sql_for_engine, test_field_name)
3
Example 11
@cached_property
def databases(self):
if self._databases is None:
self._databases = settings.DATABASES
if self._databases == {}:
self._databases = {
DEFAULT_DB_ALIAS: {
'ENGINE': 'django.db.backends.dummy',
},
}
if self._databases[DEFAULT_DB_ALIAS] == {}:
self._databases[DEFAULT_DB_ALIAS]['ENGINE'] = 'django.db.backends.dummy'
if DEFAULT_DB_ALIAS not in self._databases:
raise ImproperlyConfigured("You must define a '%s' database" % DEFAULT_DB_ALIAS)
return self._databases
3
Example 12
def recover(self):
connections[self.DB_ALIAS].close()
settings.DATABASES[self.DB_ALIAS] = self.RECOVERY_SETTINGS[self.DB_ALIAS]
del self.RECOVERY_SETTINGS[self.DB_ALIAS]
self.reload_settings()
super(Database, self).recover()
3
Example 13
Project: pootle Source File: checks.py
@checks.register()
def check_db_transaction_hooks(app_configs=None, **kwargs):
from django.conf import settings
errors = []
if settings.DATABASES['default']['ENGINE'].startswith("transaction_hooks"):
errors.append(checks.Critical(
_("Database connection uses transaction_hooks."),
hint=_("Set the DATABASES['default']['ENGINE'] to use a Django "
"backend from django.db.backends."),
id="pootle.C006",
))
return errors
3
Example 14
def db_show(request):
cars = models.Car.objects.all()
number = len(cars)
cars.delete()
engine = settings.DATABASES['default']['ENGINE']
context = {'content': '%s: %s' %(engine, number)}
return render_to_response('content.html', context)
3
Example 15
@cached_property
def databases(self):
if self._databases is None:
self._databases = settings.DATABASES
if self._databases == {}:
self._databases = {
DEFAULT_DB_ALIAS: {
'ENGINE': 'django.db.backends.dummy',
},
}
if DEFAULT_DB_ALIAS not in self._databases:
raise ImproperlyConfigured("You must define a '%s' database" % DEFAULT_DB_ALIAS)
return self._databases
3
Example 16
def _get_database(self, options):
"""Get the database to restore."""
database_name = options.get('database')
if not database_name:
if len(settings.DATABASES) > 1:
errmsg = "Because this project contains more than one database, you"\
" must specify the --database option."
raise CommandError(errmsg)
database_name = list(settings.DATABASES.keys())[0]
if database_name not in settings.DATABASES:
raise CommandError("Database %s does not exist." % database_name)
return database_name, settings.DATABASES[database_name]
3
Example 17
def setUp(self):
self.db_alias2 = next(alias for alias in settings.DATABASES
if alias != DEFAULT_DB_ALIAS)
self.cache_alias2 = next(alias for alias in settings.CACHES
if alias != DEFAULT_CACHE_ALIAS)
self.t1 = Test.objects.create(name='test1')
self.t2 = Test.objects.using(self.db_alias2).create(name='test2')
self.u = User.objects.create_user('test')
3
Example 18
Project: edx-ora Source File: reset_test_db.py
def handle(self, *args, **options):
if settings.DATABASES['default']['NAME']=='test_essaydb':
management.call_command('syncdb', interactive=False)
management.call_command('migrate', interactive=False)
for sub in Submission.objects.all():
sub.delete()
for grade in Grader.objects.all():
grade.delete()
for cm in CreatedModel.objects.all():
cm.delete()
util.update_users_from_file()
3
Example 19
Project: autotest Source File: readonly_connection.py
def _get_readonly_connection(self):
_default_db = settings.DATABASES['default']
_default_db['HOST'] = _default_db['READONLY_HOST']
_default_db['USER'] = _default_db['READONLY_USER']
_default_db['PASSWORD'] = _default_db['READONLY_PASSWORD']
reload(django_db)
# cursor() causes a new connection to be created
cursor = django_db.connection.cursor()
assert django_db.connection.connection is not None
return django_db.connection.connection
3
Example 20
def _db_cursor(self):
"""Return a database cursor to the read replica if one is available. """
# Use the read replica if one has been configured
db_alias = (
'read_replica'
if 'read_replica' in settings.DATABASES
else 'default'
)
return connections[db_alias].cursor()
3
Example 21
def handle(self, *args, **kwargs):
rocket_engine.on_appengine = True
self.reload_settings()
db.connections = db.utils.ConnectionHandler(settings.DATABASES)
db.router = db.utils.ConnectionRouter(settings.DATABASE_ROUTERS)
management.call_command(*args, **kwargs)
3
Example 22
def handle(self, output_file, *args, **kwargs):
proc = subprocess.Popen('PGPASSWORD="{password}" pg_dump -U {user} {db} > {output_file}'.format(
password=settings.DATABASES['default']['PASSWORD'],
user=settings.DATABASES['default']['USER'],
db=settings.DATABASES['default']['NAME'],
output_file=output_file,
), shell=True)
proc.communicate()
3
Example 23
def no_backend(test_func, backend):
"Use this decorator to disable test on specified backend."
if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'].rsplit('.')[-1] == backend:
@skip("This test is skipped on '%s' backend" % backend)
def inner():
pass
return inner
else:
return test_func
3
Example 24
def failover(self):
connections[self.DB_ALIAS].close()
self.RECOVERY_SETTINGS[self.DB_ALIAS] = settings.DATABASES[self.DB_ALIAS]
settings.DATABASES[self.DB_ALIAS] = settings.DATABASES[self.FAILOVER_DB_ALIAS]
self.reload_settings()
super(Database, self).failover()
3
Example 25
def handle(self, *args, **options):
"""Get necessary options from settings and give to the backup command"""
gpg_home = getattr(settings, "BACKUP_GPG_HOME", None)
backup_dir = getattr(settings, "BACKUP_DIR", None)
recipients = getattr(settings, "BACKUP_RECIPIENTS", None)
self.validate_options(backup_dir, recipients)
# Make sure the recipients is a list
if isinstance(recipients, basestring):
recipients = recipients.split(",")
try:
with BackupStorage() as storage:
destination = backup(settings.DATABASES['default'], recipients, backup_dir, gpg_home=gpg_home)
storage.move_from(destination, backup_dir)
except FailedBackup as error:
raise CommandError("{0}: {1}".format(error.__class__.__name__, error))
3
Example 26
Project: cgstudiomap Source File: creation.py
def _switch_to_test_user(self, parameters):
"""
Oracle doesn't have the concept of separate databases under the same user.
Thus, we use a separate user (see _create_test_db). This method is used
to switch to that user. We will need the main user again for clean-up when
we end testing, so we keep its credentials in SAVED_USER/SAVED_PASSWORD
entries 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']
3
Example 27
Project: cyme Source File: base.py
def syncdb(self, interactive=True):
from django.conf import settings
from django.db.utils import DEFAULT_DB_ALIAS
dbconf = settings.DATABASES[DEFAULT_DB_ALIAS]
if dbconf['ENGINE'] == 'django.db.backends.sqlite3':
if Path(dbconf['NAME']).absolute().exists():
return
gp, getpass.getpass = getpass.getpass, getpass.fallback_getpass
try:
self.management.call_command('syncdb', interactive=interactive)
finally:
getpass.getpass = gp
3
Example 28
def handle(self, *args, **options):
database = options.get('database', 'default')
if (settings.DATABASES[database]['ENGINE'] == 'django_tenants.postgresql_backend' and not
django_is_in_test_mode()):
raise CommandError("syncdb has been disabled, for database '{0}'. "
"Use migrate_schemas instead. Please read the "
"docuementation if you don't know why "
"you shouldn't call syncdb directly!".format(database))
super(Command, self).handle(*args, **options)
3
Example 29
Project: doc-versions Source File: models.py
@classmethod
def bulk_ids(cls, n):
assert n >= 0
if n == 0:
return []
if 'postgresql' in settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE']:
cursor = connection.cursor()
sql = "select nextval('%s_id_seq') from generate_series(1,%d)"\
% (cls._meta.db_table, n)
cursor.execute(sql)
return [int(r[0]) for r in cursor]
elif 'sqlite' in settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE']:
m = cls.objects.aggregate(models.Max('id'))['id__max']
if m is None:
m = 0
return range(m + 1, n + m + 1)
raise NotImplementedError
3
Example 30
def get_cmd_options():
"Obtains the command-line PostgreSQL connection options for shell commands."
# The db_name parameter is optional
options = ''
db_settings = settings.DATABASES['default']
if db_settings['NAME']:
options += '-d %s ' % db_settings['NAME']
if db_settings['USER']:
options += '-U %s ' % db_settings['USER']
if db_settings['HOST']:
options += '-h %s ' % db_settings['HOST']
if db_settings['PORT']:
options += '-p %s ' % db_settings['PORT']
return options
3
Example 31
def handle(self, **options):
dbpath = settings.DATABASES['default']['NAME']
if os.path.exists(dbpath):
self.stdout.write(Term.warn('Removing old database %s' % dbpath))
os.remove(dbpath)
self.stdout.write(Term.info('Creating database %s' % dbpath))
if IS_1_7:
call_command('migrate', noinput=True, load_initial_data=False, interactive=False)
else:
call_command('syncdb', noinput=True, load_initial_data=False, interactive=False)
User.objects.create_superuser('admin', '[email protected]', 'password')
print('Done.\n\nCreating sample data...')
create_sample_data()
print('Done\n')
3
Example 32
Project: django-simple-history Source File: models.py
def convert_auto_field(field):
"""Convert AutoField to a non-incrementing type
The historical model gets its own AutoField, so any existing one
must be replaced with an IntegerField.
"""
connection = router.db_for_write(field.model)
if settings.DATABASES[connection]['ENGINE'] in ('django_mongodb_engine',):
# Check if AutoField is string for django-non-rel support
return models.TextField
return models.IntegerField
3
Example 33
def install(settings=settings):
from dbroutes.utils import PartitionConnectionHandler
from django import db
handler = PartitionConnectionHandler(settings.DATABASES)
db.connections.__class__ = type(handler)
db.connections.__dict__ = vars(handler)
3
Example 34
Project: autotest Source File: readonly_connection.py
def _restore_django_state(self):
django_db.connection.connection = self._old_connection
_default_db = settings.DATABASES['default']
_default_db['HOST'] = self._old_host
_default_db['USER'] = self._old_username
_default_db['PASSWORD'] = self._old_password
3
Example 35
Project: djangosnippets.org Source File: tests.py
def skipUnlessDB(engine):
"""
This decorator makes a test skip unless the current connection uses the
specified engine.
"""
from django.conf import settings
actual_engine = settings.DATABASES['default']['ENGINE']
if engine not in actual_engine:
return unittest.skip(
'Unsupported connection engine: %s (expected %s)' % (
actual_engine, engine
))
return lambda func: func
3
Example 36
Project: django-cachalot Source File: panels.py
def collect_invalidations(self):
models = apps.get_models()
data = defaultdict(list)
for db_alias in settings.DATABASES:
model_cache_keys = dict(
[(_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()})
3
Example 37
@classmethod
def setUpClass(cls):
super(BaseTestCase, cls).setUpClass()
cls.ldap_server = volatildap.LdapServer(
initial_data=cls.directory,
schemas=['core.schema', 'cosine.schema', 'inetorgperson.schema', 'nis.schema'],
)
settings.DATABASES['ldap']['USER'] = cls.ldap_server.rootdn
settings.DATABASES['ldap']['PASSWORD'] = cls.ldap_server.rootpw
settings.DATABASES['ldap']['NAME'] = cls.ldap_server.uri
3
Example 38
def no_backend(test_func, backend):
"Use this decorator to disable test on specified backend."
if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'].rsplit('.')[-1] == backend:
return pass_test
else:
return test_func
3
Example 39
Project: django-fabtastic Source File: util.py
def get_db_setting(db_setting, db_alias='default'):
"""
Gets a database setting from settings.py.
db_setting: (str) One of the database setting names.
For example, 'NAME', 'PORT', 'HOST'.
db_alias: (str) In the case of settings in Django 1.2 format, get settings
for a DB other than the default.
"""
return settings.DATABASES[db_alias].get(db_setting, '')
3
Example 40
Project: django-cachalot Source File: api.py
@skipIf(len(settings.DATABASES) == 1,
'We can’t change the DB used since there’s only one configured')
def test_invalidate_cachalot_multi_db(self):
with self.assertNumQueries(1):
self.assertListEqual(list(Test.objects.all()), [self.t1])
call_command('invalidate_cachalot', verbosity=0,
db_alias=self.db_alias2)
with self.assertNumQueries(0):
self.assertListEqual(list(Test.objects.all()), [self.t1])
with self.assertNumQueries(1, using=self.db_alias2):
self.assertListEqual(list(Test.objects.using(self.db_alias2)),
[self.t2])
call_command('invalidate_cachalot', verbosity=0,
db_alias=self.db_alias2)
with self.assertNumQueries(1, using=self.db_alias2):
self.assertListEqual(list(Test.objects.using(self.db_alias2)),
[self.t2])
3
Example 41
def _use_read_replica(self, queryset):
"""
Use the read replica if it's available.
Args:
queryset (QuerySet)
Returns:
QuerySet
"""
return (
queryset.using("read_replica")
if "read_replica" in settings.DATABASES
else queryset
)
3
Example 42
def get_connection_string():
"""Return the database connection string"""
db = settings.DATABASES['default']
if 'postgres' not in db['ENGINE']:
raise ValueError("Billing API only supports PostGreSQL.")
return "host='%s' dbname='%s' user='%s' password='%s'" \
% (db.get('HOST', 'localhost'), db.get('NAME'), db.get('USER'),
db.get('PASSWORD'))
3
Example 43
Project: edx-platform Source File: models.py
@classmethod
def all_submitted_problems_read_only(cls, course_id):
"""
Return all model instances that correspond to problems that have been
submitted for a given course. So module_type='problem' and a non-null
grade. Use a read replica if one exists for this environment.
"""
queryset = cls.objects.filter(
course_id=course_id,
module_type='problem',
grade__isnull=False
)
if "read_replica" in settings.DATABASES:
return queryset.using("read_replica")
else:
return queryset
3
Example 44
def backwards(self, orm):
# Deleting model 'StoredOEmbed'
db.delete_table('oembed_storedoembed')
# Removing unique constraint on 'StoredOEmbed', fields ['match', 'maxwidth', 'maxheight']
if 'mysql' not in settings.DATABASES['default']['ENGINE']:
db.delete_unique('oembed_storedoembed', ['match', 'maxwidth', 'maxheight'])
# Deleting model 'StoredProvider'
db.delete_table('oembed_storedprovider')
# Deleting model 'AggregateMedia'
db.delete_table('oembed_aggregatemedia')
3
Example 45
def __init__(self, db_name, database_sig=None):
database_sig = database_sig or {}
try:
from django.db import connections
engine = settings.DATABASES[db_name]['ENGINE'].split('.')[-1]
connection = connections[db_name]
module_name = ['django_evolution.db', engine]
module = __import__('.'.join(module_name), {}, {}, [''])
self.evolver = module.EvolutionOperations(database_sig, connection)
except ImportError:
if hasattr(settings, 'DATABASE_ENGINE'):
module_name = ['django_evolution.db', settings.DATABASE_ENGINE]
module = __import__('.'.join(module_name), {}, {}, [''])
self.evolver = module.EvolutionOperations(database_sig)
else:
raise
3
Example 46
Project: django-mongokit Source File: tests.py
def test_create_test_database_by_specific_bad_name(self):
from django.conf import settings
try:
assert 'mongodb' in settings.DATABASES
except AttributeError:
# Django <1.2
return
settings.DATABASES['mongodb']['TEST_NAME'] = "muststartwith__test_"
from django.db import connections
connection = connections['mongodb']
# why doesn't this work?!?!
#from mongodb.base import DatabaseError
#self.assertRaises(DatabaseError, connection.creation.create_test_db)
self.assertRaises(Exception, connection.creation.create_test_db)
3
Example 47
Project: autotest Source File: readonly_connection.py
def _save_django_state(self):
self._old_connection = django_db.connection.connection
_default_db = settings.DATABASES['default']
self._old_host = _default_db['HOST']
self._old_username = _default_db['USER']
self._old_password = _default_db['PASSWORD']
3
Example 48
@register()
def db_check(app_configs, **kwargs):
errors = []
try:
supported_driver = 'django.db.backends.postgresql_psycopg2'
if settings.DATABASES['default']['ENGINE'] != supported_driver:
raise ValueError()
except (AttributeError, KeyError, ValueError):
errors.append(Critical(msg='Misago requires PostgreSQL database.',
id='misago.001'))
return errors
3
Example 49
def handle(self, *args, **options):
"""Get necessary options from settings and give to the restore command"""
gpg_home = getattr(settings, "BACKUP_GPG_HOME", None)
restore_from = options["restore_from"]
try:
with self.restore_location(restore_from) as restore_location:
restore(settings.DATABASES['default'], restore_location, gpg_home=gpg_home)
except FailedBackup as error:
raise CommandError("{0}: {1}".format(error.__class__.__name__, error))
3
Example 50
Project: cgstudiomap Source File: creation.py
@cached_property
def _maindb_connection(self):
"""
This is analogous to other backends' `_nodb_connection` property,
which allows access to an "administrative" connection which can
be used to manage the test databases.
For Oracle, the only connection that can be used for that purpose
is the main (non-test) connection.
"""
settings_dict = settings.DATABASES[self.connection.alias]
user = settings_dict.get('SAVED_USER') or settings_dict['USER']
password = settings_dict.get('SAVED_PASSWORD') or settings_dict['PASSWORD']
settings_dict = settings_dict.copy()
settings_dict.update(USER=user, PASSWORD=password)
DatabaseWrapper = type(self.connection)
return DatabaseWrapper(settings_dict, alias=self.connection.alias)