本文整理汇总了Python中django.db.connection.ensure_connection方法的典型用法代码示例。如果您正苦于以下问题:Python connection.ensure_connection方法的具体用法?Python connection.ensure_connection怎么用?Python connection.ensure_connection使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db.connection
的用法示例。
在下文中一共展示了connection.ensure_connection方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: check_database_connected
# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import ensure_connection [as 别名]
def check_database_connected(app_configs, **kwargs):
"""
A Django check to see if connecting to the configured default
database backend succeeds.
"""
errors = []
try:
connection.ensure_connection()
except OperationalError as e:
msg = "Could not connect to database: {!s}".format(e)
errors.append(checks.Error(msg, id=health.ERROR_CANNOT_CONNECT_DATABASE))
except ImproperlyConfigured as e:
msg = 'Datbase misconfigured: "{!s}"'.format(e)
errors.append(checks.Error(msg, id=health.ERROR_MISCONFIGURED_DATABASE))
else:
if not connection.is_usable():
errors.append(
checks.Error(
"Database connection is not usable",
id=health.ERROR_UNUSABLE_DATABASE,
)
)
return errors
示例2: handle
# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import ensure_connection [as 别名]
def handle(self, *args, **options):
max_retries = options['max_retries']
poll_seconds = options['poll_seconds']
for retry in range(max_retries):
try:
connection.ensure_connection()
except OperationalError as ex:
self.stdout.write(
'Database unavailable on attempt {attempt}/{max_retries}:'
' {error}'.format(
attempt=retry + 1,
max_retries=max_retries,
error=ex))
time.sleep(poll_seconds)
else:
break
else:
self.stdout.write(self.style.ERROR('Database unavailable'))
sys.exit(1)
示例3: test_ignores_connection_configuration_queries
# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import ensure_connection [as 别名]
def test_ignores_connection_configuration_queries(self):
real_ensure_connection = connection.ensure_connection
connection.close()
def make_configuration_query():
is_opening_connection = connection.connection is None
real_ensure_connection()
if is_opening_connection:
# Avoid infinite recursion. Creating a cursor calls
# ensure_connection() which is currently mocked by this method.
connection.cursor().execute('SELECT 1' + connection.features.bare_select_suffix)
ensure_connection = 'django.db.backends.base.base.BaseDatabaseWrapper.ensure_connection'
with mock.patch(ensure_connection, side_effect=make_configuration_query):
with self.assertNumQueries(1):
list(Car.objects.all())
示例4: connected
# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import ensure_connection [as 别名]
def connected():
"""Context manager that ensures we're connected to the database.
If there is not yet a connection to the database, this will connect on
entry and disconnect on exit. Preexisting connections will be left alone.
If the preexisting connection is not usable it is closed and a new
connection is made.
"""
if connection.connection is None:
connection.close_if_unusable_or_obsolete()
connection.ensure_connection()
try:
yield
finally:
connection.close()
elif connection.is_usable():
yield
else:
# Connection is not usable, so we disconnect and reconnect. Since
# the connection was previously connected we do not disconnect this
# new connection.
connection.close_if_unusable_or_obsolete()
connection.ensure_connection()
yield
示例5: test_disconnects_and_reconnects_if_not_usable
# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import ensure_connection [as 别名]
def test_disconnects_and_reconnects_if_not_usable(self):
connection.ensure_connection()
preexisting_connection = connection.connection
connection.errors_occurred = True
self.patch(connection, "is_usable").return_value = False
self.assertThat(connection.connection, Not(Is(None)))
with orm.connected():
self.assertThat(
connection.connection, Not(Is(preexisting_connection))
)
self.assertThat(connection.connection, Not(Is(None)))
self.assertThat(connection.connection, Not(Is(preexisting_connection)))
self.assertThat(connection.connection, Not(Is(None)))
示例6: test_leaves_preexisting_connections_open
# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import ensure_connection [as 别名]
def test_leaves_preexisting_connections_open(self):
# Ensure there's a database connection to begin with.
connection.ensure_connection()
# No transaction has been entered (what Django calls an atomic block),
# but the connection has been established.
self.assertFalse(connection.in_atomic_block)
self.expectThat(connection.connection, Not(Is(None)))
# Call a function via the `transactional` decorator.
decorated_function = orm.transactional(lambda: None)
decorated_function()
# After the decorated function has returned the transaction has
# been exited, but the preexisting connection remains open.
self.assertFalse(connection.in_atomic_block)
self.expectThat(connection.connection, Not(Is(None)))
示例7: _ensureConnection
# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import ensure_connection [as 别名]
def _ensureConnection(self):
# If connection is already made close it.
from django.db import connection
if connection.connection is not None:
connection.close()
# Loop forever until a connection can be made.
while True:
try:
connection.ensure_connection()
except Exception:
log.err(
_why=(
"Error starting: "
"Connection to database cannot be established."
)
)
time.sleep(1)
else:
# Connection made, now close it.
connection.close()
break
示例8: test_prehook
# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import ensure_connection [as 别名]
def test_prehook(self) -> None:
cb = Mock(name='pre_reconnect_hook')
ddr.pre_reconnect.connect(cb)
self.assertRaises(OperationalError, connection.ensure_connection)
self.assertTrue(cb.called)
del connection._connection_retries
示例9: test_posthook
# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import ensure_connection [as 别名]
def test_posthook(self) -> None:
cb = Mock(name='post_reconnect_hook')
ddr.post_reconnect.connect(cb)
self.assertRaises(OperationalError, connection.ensure_connection)
self.assertTrue(cb.called)
del connection._connection_retries
示例10: get_sqlalchemy_connection
# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import ensure_connection [as 别名]
def get_sqlalchemy_connection() -> sqlalchemy.engine.base.Connection:
global sqlalchemy_engine
if sqlalchemy_engine is None:
def get_dj_conn() -> TimeTrackingConnection:
connection.ensure_connection()
return connection.connection
sqlalchemy_engine = sqlalchemy.create_engine('postgresql://',
creator=get_dj_conn,
poolclass=NonClosingPool,
pool_reset_on_return=False)
sa_connection = sqlalchemy_engine.connect()
sa_connection.execution_options(autocommit=False)
return sa_connection
示例11: _generate_database_status
# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import ensure_connection [as 别名]
def _generate_database_status(self):
"""Generates the database status message
:return: JSON describing the database status
:rtype: dict
"""
try:
connection.ensure_connection()
status_dict = {'OK': True, 'detail': {'msg': 'Database alive and well'}, 'errors': [], 'warnings': []}
except Exception as ex:
status_dict = {'OK': False, 'detail': {'msg': 'Unable to connect to database'}, 'errors': [{'OPERATIONAL_ERROR': 'Database unavailable.'}], 'warnings': []}
return status_dict
示例12: test_client_encoding
# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import ensure_connection [as 别名]
def test_client_encoding(self):
"""Client encoding is set correctly."""
connection.ensure_connection()
self.assertEqual(connection.connection.encoding, 'UTF-8')
self.assertEqual(connection.connection.nencoding, 'UTF-8')
示例13: __enter__
# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import ensure_connection [as 别名]
def __enter__(self):
"""Assert that no connections are yet open."""
for alias in connections:
connections[alias].ensure_connection()
示例14: test_leaves_preexisting_connections_alone
# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import ensure_connection [as 别名]
def test_leaves_preexisting_connections_alone(self):
connection.ensure_connection()
preexisting_connection = connection.connection
self.assertThat(connection.connection, Not(Is(None)))
with orm.connected():
self.assertThat(connection.connection, Is(preexisting_connection))
self.assertThat(connection.connection, Is(preexisting_connection))
示例15: test_exit_removes_block_on_database_connections
# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import ensure_connection [as 别名]
def test_exit_removes_block_on_database_connections(self):
with TotallyDisconnected():
self.assertRaises(RuntimeError, getattr, connection, "connect")
connection.ensure_connection()