Python django.db.connection.is_usable() Examples
The following are 12
code examples of django.db.connection.is_usable().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.db.connection
, or try the search function
.
Example #1
Source File: db.py From django-htk with MIT License | 8 votes |
def ensure_mysql_connection_usable(): """Ensure that MySQL connection is usable From: http://stackoverflow.com/questions/7835272/django-operationalerror-2006-mysql-server-has-gone-away """ from django.db import connection, connections # MySQL is lazily connected to in Django. # connection.connection is None means # you have not connected to MySQL before if connection.connection and not connection.is_usable(): # destroy the default MySQL connection # after this line, when you use ORM methods # Django will reconnect to the default MySQL # # Delete one database connection: # del connections._connections.default # # Delete all database connections databases = connections._connections.__dict__.keys() for database in databases: del connections._connections.__dict__[database]
Example #2
Source File: checks.py From python-dockerflow with Mozilla Public License 2.0 | 6 votes |
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
Example #3
Source File: orm.py From maas with GNU Affero General Public License v3.0 | 6 votes |
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
Example #4
Source File: __init__.py From django-dbconn-retry with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_ensure_closed(self) -> None: from django.db import connection connection.close() self.assertFalse(connection.is_usable()) # should be true after setUp
Example #5
Source File: __init__.py From django-dbconn-retry with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_prehook(self) -> None: cb = Mock(name='pre_reconnect_hook') ddr.pre_reconnect.connect(fix_connection) ddr.pre_reconnect.connect(cb) from django.db import connection connection.close() connection.s_connect = connection.connect connection.connect = Mock(side_effect=OperationalError('reconnect testing')) connection.ensure_connection() ReconnectTests.cls_atomics['default'] = transaction.atomic(using='default') ReconnectTests.cls_atomics['default'].__enter__() self.assertTrue(cb.called) self.assertTrue(connection.is_usable())
Example #6
Source File: __init__.py From django-dbconn-retry with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_posthook(self) -> None: cb = Mock(name='post_reconnect_hook') ddr.pre_reconnect.connect(fix_connection) ddr.post_reconnect.connect(cb) from django.db import connection connection.close() connection.s_connect = connection.connect connection.connect = Mock(side_effect=OperationalError('reconnect testing')) connection.ensure_connection() ReconnectTests.cls_atomics['default'] = transaction.atomic(using='default') ReconnectTests.cls_atomics['default'].__enter__() self.assertTrue(cb.called) self.assertTrue(connection.is_usable())
Example #7
Source File: testcases.py From bioforum with MIT License | 5 votes |
def _should_check_constraints(self, connection): return ( connection.features.can_defer_constraint_checks and not connection.needs_rollback and connection.is_usable() )
Example #8
Source File: queue_processors.py From zulip with Apache License 2.0 | 5 votes |
def check_and_send_restart_signal() -> None: try: if not connection.is_usable(): logging.warning("*** Sending self SIGUSR1 to trigger a restart.") os.kill(os.getpid(), signal.SIGUSR1) except Exception: pass
Example #9
Source File: testcases.py From Hands-On-Application-Development-with-PyCharm with MIT License | 5 votes |
def _should_check_constraints(self, connection): return ( connection.features.can_defer_constraint_checks and not connection.needs_rollback and connection.is_usable() )
Example #10
Source File: testcases.py From python with Apache License 2.0 | 5 votes |
def _should_check_constraints(self, connection): return ( connection.features.can_defer_constraint_checks and not connection.needs_rollback and connection.is_usable() )
Example #11
Source File: testcases.py From python2017 with MIT License | 5 votes |
def _should_check_constraints(self, connection): return ( connection.features.can_defer_constraint_checks and not connection.needs_rollback and connection.is_usable() )
Example #12
Source File: execute_sql.py From Archery with Apache License 2.0 | 4 votes |
def execute_callback(task): """异步任务的回调, 将结果填入数据库等等 使用django-q的hook, 传入参数为整个task task.result 是真正的结果 """ # https://stackoverflow.com/questions/7835272/django-operationalerror-2006-mysql-server-has-gone-away if connection.connection and not connection.is_usable(): close_old_connections() workflow_id = task.args[0] # 判断工单状态,如果不是执行中的,不允许更新信息,直接抛错记录日志 with transaction.atomic(): workflow = SqlWorkflow.objects.get(id=workflow_id) if workflow.status != 'workflow_executing': raise Exception(f'工单{workflow.id}状态不正确,禁止重复更新执行结果!') workflow.finish_time = task.stopped if not task.success: # 不成功会返回错误堆栈信息,构造一个错误信息 workflow.status = 'workflow_exception' execute_result = ReviewSet(full_sql=workflow.sqlworkflowcontent.sql_content) execute_result.rows = [ReviewResult( stage='Execute failed', errlevel=2, stagestatus='异常终止', errormessage=task.result, sql=workflow.sqlworkflowcontent.sql_content)] elif task.result.warning or task.result.error: execute_result = task.result workflow.status = 'workflow_exception' else: execute_result = task.result workflow.status = 'workflow_finish' # 保存执行结果 workflow.sqlworkflowcontent.execute_result = execute_result.json() workflow.sqlworkflowcontent.save() workflow.save() # 增加工单日志 audit_id = Audit.detail_by_workflow_id(workflow_id=workflow_id, workflow_type=WorkflowDict.workflow_type['sqlreview']).audit_id Audit.add_log(audit_id=audit_id, operation_type=6, operation_type_desc='执行结束', operation_info='执行结果:{}'.format(workflow.get_status_display()), operator='', operator_display='系统' ) # DDL工单结束后清空实例资源缓存 if workflow.syntax_type == 1: r = get_redis_connection("default") for key in r.scan_iter(match='*insRes*', count=2000): r.delete(key) # 发送消息 notify_for_execute(workflow)