本文整理汇总了Python中django.db.connections.databases方法的典型用法代码示例。如果您正苦于以下问题:Python connections.databases方法的具体用法?Python connections.databases怎么用?Python connections.databases使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db.connections
的用法示例。
在下文中一共展示了connections.databases方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from django.db import connections [as 别名]
# 或者: from django.db.connections import databases [as 别名]
def __init__(self, database, read=True, write=False):
self.read = read
self.write = write
self.created_db_config = False
if isinstance(database, str):
self.database = database
elif isinstance(database, dict):
# Note: this invalidates the docs above. Update them
# eventually.
self.created_db_config = True
self.unique_db_id = str(uuid4())
connections.databases[self.unique_db_id] = database
self.database = self.unique_db_id
else:
msg = ("database must be an identifier for an existing db, "
"or a complete configuration.")
raise ValueError(msg)
示例2: get_client_source_data_connection
# 需要导入模块: from django.db import connections [as 别名]
# 或者: from django.db.connections import databases [as 别名]
def get_client_source_data_connection():
from footprint.client.configuration.utils import resolve_fixture
from footprint.client.configuration.fixture import InitFixture
source_db = resolve_fixture(None, 'init', InitFixture).import_database()
source_db['ENGINE'] = 'django.contrib.gis.db.backends.postgis'
source_db['OPTIONS'] = {'autocommit': True}
source_db['NAME'] = source_db['database']
source_db['PASSWORD'] = source_db['password']
source_db['USER'] = source_db['user']
source_db['HOST'] = source_db['host']
logger.info("Connecting to database {db} on {host}".format(db=source_db['NAME'], host=source_db['HOST']))
connections.databases['import'] = source_db
return connections['import']
示例3: test_isolation_level_is_serializable
# 需要导入模块: from django.db import connections [as 别名]
# 或者: from django.db.connections import databases [as 别名]
def test_isolation_level_is_serializable(self):
# Transactions *must* be SERIALIZABLE for the default connection.
self.assertThat(
connections.databases,
ContainsDict(
{
"default": ContainsDict(
{
"OPTIONS": ContainsDict(
{
"isolation_level": Equals(
ISOLATION_LEVEL_REPEATABLE_READ
)
}
)
}
)
}
),
)
示例4: test_cleans_up
# 需要导入模块: from django.db import connections [as 别名]
# 或者: from django.db.connections import databases [as 别名]
def test_cleans_up(self):
starting_connections = len(connections.databases)
with in_database(self.test_db_config, write=True):
G(TestModel, name='Sue')
ending_connections = len(connections.databases)
self.assertEqual(starting_connections, ending_connections)
示例5: __exit__
# 需要导入模块: from django.db import connections [as 别名]
# 或者: from django.db.connections import databases [as 别名]
def __exit__(self, exc_type, exc_value, traceback):
THREAD_LOCAL.DB_FOR_READ_OVERRIDE.pop()
THREAD_LOCAL.DB_FOR_WRITE_OVERRIDE.pop()
if self.created_db_config:
connections[self.unique_db_id].close()
del connections.databases[self.unique_db_id]
示例6: ExportMigrations
# 需要导入模块: from django.db import connections [as 别名]
# 或者: from django.db.connections import databases [as 别名]
def ExportMigrations():
"""Exports counts of unapplied migrations.
This is meant to be called during app startup, ideally by
django_prometheus.apps.AppConfig.
"""
# Import MigrationExecutor lazily. MigrationExecutor checks at
# import time that the apps are ready, and they are not when
# django_prometheus is imported. ExportMigrations() should be
# called in AppConfig.ready(), which signals that all apps are
# ready.
from django.db.migrations.executor import MigrationExecutor
if "default" in connections and (
isinstance(connections["default"], DatabaseWrapper)
):
# This is the case where DATABASES = {} in the configuration,
# i.e. the user is not using any databases. Django "helpfully"
# adds a dummy database and then throws when you try to
# actually use it. So we don't do anything, because trying to
# export stats would crash the app on startup.
return
for alias in connections.databases:
executor = MigrationExecutor(connections[alias])
ExportMigrationsForDatabase(alias, executor)
示例7: mock_django_connection
# 需要导入模块: from django.db import connections [as 别名]
# 或者: from django.db.connections import databases [as 别名]
def mock_django_connection(disabled_features=None):
""" Overwrite the Django database configuration with a mocked version.
This is a helper function that does the actual monkey patching.
"""
db = connections.databases['default']
db['PASSWORD'] = '****'
db['USER'] = '**Database disabled for unit tests**'
ConnectionHandler.__getitem__ = MagicMock(name='mock_connection')
# noinspection PyUnresolvedReferences
mock_connection = ConnectionHandler.__getitem__.return_value
if disabled_features:
for feature in disabled_features:
setattr(mock_connection.features, feature, False)
mock_ops = mock_connection.ops
# noinspection PyUnusedLocal
def compiler(queryset, connection, using, **kwargs):
result = MagicMock(name='mock_connection.ops.compiler()')
# noinspection PyProtectedMember
result.execute_sql.side_effect = NotSupportedError(
"Mock database tried to execute SQL for {} model.".format(
queryset.model._meta.object_name))
result.has_results.side_effect = result.execute_sql.side_effect
return result
mock_ops.compiler.return_value.side_effect = compiler
mock_ops.integer_field_range.return_value = (-sys.maxsize - 1, sys.maxsize)
mock_ops.max_name_length.return_value = sys.maxsize
Model.refresh_from_db = Mock() # Make this into a noop.
示例8: test_backend_db
# 需要导入模块: from django.db import connections [as 别名]
# 或者: from django.db.connections import databases [as 别名]
def test_backend_db():
"""Ensure that we are always testing sqlite on fast in memory DB"""
from django.db import connection, connections
if connection.vendor == "sqlite":
assert "file:memorydb" in connections.databases["default"]["NAME"]
示例9: test_time_zone_parameter_not_supported_if_database_supports_timezone
# 需要导入模块: from django.db import connections [as 别名]
# 或者: from django.db.connections import databases [as 别名]
def test_time_zone_parameter_not_supported_if_database_supports_timezone(self):
connections.databases['tz'] = connections.databases['default'].copy()
connections.databases['tz']['TIME_ZONE'] = 'Asia/Bangkok'
tz_conn = connections['tz']
try:
with self.assertRaises(ImproperlyConfigured):
tz_conn.cursor()
finally:
connections['tz'].close() # in case the test fails
del connections['tz']
del connections.databases['tz']
示例10: test_time_zone_parameter_not_supported_if_database_supports_timezone
# 需要导入模块: from django.db import connections [as 别名]
# 或者: from django.db.connections import databases [as 别名]
def test_time_zone_parameter_not_supported_if_database_supports_timezone(self):
connections.databases['tz'] = connections.databases['default'].copy()
connections.databases['tz']['TIME_ZONE'] = 'Asia/Bangkok'
tz_conn = connections['tz']
try:
msg = (
"Connection 'tz' cannot set TIME_ZONE because its engine "
"handles time zones conversions natively."
)
with self.assertRaisesMessage(ImproperlyConfigured, msg):
tz_conn.cursor()
finally:
connections['tz'].close() # in case the test fails
del connections['tz']
del connections.databases['tz']
示例11: createConnection
# 需要导入模块: from django.db import connections [as 别名]
# 或者: from django.db.connections import databases [as 别名]
def createConnection(self):
"""Create new database connection."""
db = connections.databases[self.alias]
backend = load_backend(db["ENGINE"])
return backend.DatabaseWrapper(
db, self.alias, allow_thread_sharing=True
)
示例12: test_atomic_requests_are_enabled
# 需要导入模块: from django.db import connections [as 别名]
# 或者: from django.db.connections import databases [as 别名]
def test_atomic_requests_are_enabled(self):
# ATOMIC_REQUESTS *must* be set for the default connection.
self.assertThat(
connections.databases,
ContainsDict(
{"default": ContainsDict({"ATOMIC_REQUESTS": Is(True)})}
),
)
示例13: _get_new_connection
# 需要导入模块: from django.db import connections [as 别名]
# 或者: from django.db.connections import databases [as 别名]
def _get_new_connection(self):
"""Create new database connection."""
db = connections.databases[self.alias]
backend = load_backend(db["ENGINE"])
return backend.DatabaseWrapper(db, self.alias)
示例14: get_ogr_db_string
# 需要导入模块: from django.db import connections [as 别名]
# 或者: from django.db.connections import databases [as 别名]
def get_ogr_db_string():
"""
Construct the DB string that GDAL will use to inspect the database.
GDAL will create its own connection to the database, so we re-use the
connection settings from the Django test.
"""
db = connections.databases['default']
# Map from the django backend into the OGR driver name and database identifier
# https://www.gdal.org/ogr/ogr_formats.html
#
# TODO: Support Oracle (OCI).
drivers = {
'django.contrib.gis.db.backends.postgis': ('PostgreSQL', "PG:dbname='%(db_name)s'", ' '),
'django.contrib.gis.db.backends.mysql': ('MySQL', 'MYSQL:"%(db_name)s"', ','),
'django.contrib.gis.db.backends.spatialite': ('SQLite', '%(db_name)s', '')
}
db_engine = db['ENGINE']
if db_engine not in drivers:
return None
drv_name, db_str, param_sep = drivers[db_engine]
# Ensure that GDAL library has driver support for the database.
try:
Driver(drv_name)
except GDALException:
return None
# SQLite/SpatiaLite in-memory databases
if db['NAME'] == ":memory:":
return None
# Build the params of the OGR database connection string
params = [db_str % {'db_name': db['NAME']}]
def add(key, template):
value = db.get(key, None)
# Don't add the parameter if it is not in django's settings
if value:
params.append(template % value)
add('HOST', "host='%s'")
add('PORT', "port='%s'")
add('USER', "user='%s'")
add('PASSWORD', "password='%s'")
return param_sep.join(params)