Python django.db.connection.in_atomic_block() Examples
The following are 16
code examples of django.db.connection.in_atomic_block().
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 | 6 votes |
def close_connection(): """Closes the connection if we are not in an atomic block. The connection should never be closed if we are in an atomic block, as happens when running tests as part of a django TestCase. Otherwise, closing the connection is important to avoid a connection time out after long actions. Django does not automatically refresh a connection which has been closed due to idleness (this normally happens in the request start/finish part of a webapp's lifecycle, which this process does not have), so we must do it ourselves if the connection goes idle due to stuff taking a really long time. source: http://stackoverflow.com/a/39322632/865091 """ from django.db import connection if not connection.in_atomic_block: connection.close()
Example #2
Source File: orm.py From maas with GNU Affero General Public License v3.0 | 6 votes |
def savepoint(): """Context manager to wrap the code within a savepoint. This also enters a savepoint context for post-commit hooks, and so should always be used in preference to `transaction.atomic()` when only a savepoint is needed. If either a transaction or a savepoint within a transaction is what you want, use the `transactional` decorator. If you want a _decorator_ specifically, use the `transactional` decorator. If you want a _savepoint decorator_ specifically, write one, or adapt this to do it. """ if connection.in_atomic_block: with post_commit_hooks.savepoint(): with transaction.atomic(): yield else: raise TransactionManagementError( "Savepoints cannot be created outside of a transaction." )
Example #3
Source File: fixtures.py From maas with GNU Affero General Public License v3.0 | 6 votes |
def _setUp(self): # Must be called inside a transaction. assert connection.in_atomic_block Config.objects.set_config("rbac_url", "http://rbac.example.com") Config.objects.set_config( "external_auth_url", "https://auth.example.com" ) Config.objects.set_config("external_auth_user", "user@candid") Config.objects.set_config( "external_auth_key", "x0NeASLPFhOFfq3Q9M0joMveI4HjGwEuJ9dtX/HTSRY=" ) client = FakeRBACClient() rbac._store.client = client rbac._store.cleared = False self.store = client.store def cleanup(): rbac._store.client = None rbac.clear() self.addCleanup(cleanup)
Example #4
Source File: queue.py From django-postgres-queue with BSD 2-Clause "Simplified" License | 5 votes |
def run_once(self, exclude_ids=[]): assert not connection.in_atomic_block return self._run_once(exclude_ids=exclude_ids)
Example #5
Source File: test_locks.py From django-mysql with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_creates_an_atomic(self): assert connection.get_autocommit() == 1 assert not connection.in_atomic_block with TableLock(read=[Alphabet]): assert connection.get_autocommit() == 0 assert connection.in_atomic_block assert connection.get_autocommit() == 1 assert not connection.in_atomic_block
Example #6
Source File: views.py From Dailyfresh-B2C with Apache License 2.0 | 5 votes |
def set_rollback(): atomic_requests = connection.settings_dict.get('ATOMIC_REQUESTS', False) if atomic_requests and connection.in_atomic_block: transaction.set_rollback(True)
Example #7
Source File: views.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def in_transaction(request): return HttpResponse(str(connection.in_atomic_block))
Example #8
Source File: views.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def not_in_transaction(request): return HttpResponse(str(connection.in_atomic_block))
Example #9
Source File: views.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def in_transaction(request): return HttpResponse(str(connection.in_atomic_block))
Example #10
Source File: views.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def not_in_transaction(request): return HttpResponse(str(connection.in_atomic_block))
Example #11
Source File: compat.py From esdc-ce with Apache License 2.0 | 5 votes |
def set_rollback(): if hasattr(transaction, 'set_rollback'): if connection.settings_dict.get('ATOMIC_REQUESTS', False): # If running in >=1.6 then mark a rollback as required, # and allow it to be handled by Django. if connection.in_atomic_block: transaction.set_rollback(True) elif transaction.is_managed(): # Otherwise handle it explicitly if in managed mode. if transaction.is_dirty(): transaction.rollback() transaction.leave_transaction_management() else: # transaction not managed pass
Example #12
Source File: dblocks.py From maas with GNU Affero General Public License v3.0 | 5 votes |
def __enter__(self): """Obtain lock using pg_advisory_xact_lock().""" if not connection.in_atomic_block: raise DatabaseLockAttemptOutsideTransaction(self) with closing(connection.cursor()) as cursor: query = "SELECT %s(%%s, %%s)" % self.lock cursor.execute(query, self) if cursor.fetchone() == (False,): raise DatabaseLockNotHeld(self)
Example #13
Source File: orm.py From maas with GNU Affero General Public License v3.0 | 5 votes |
def in_transaction(_connection=None): """Is `_connection` in the midst of a transaction? This only enquires as to Django's perspective on the situation. It does not actually check that the database agrees with Django. :return: bool """ if _connection is None: return connection.in_atomic_block else: return _connection.in_atomic_block
Example #14
Source File: test_orm.py From maas with GNU Affero General Public License v3.0 | 5 votes |
def test_calls_function_within_transaction_then_closes_connections(self): # Close the database connection to begin with. connection.close() # No transaction has been entered (what Django calls an atomic block), # and the connection has not yet been established. self.assertFalse(connection.in_atomic_block) self.expectThat(connection.connection, Is(None)) def check_inner(*args, **kwargs): # In here, the transaction (`atomic`) has been started but is not # over, and the connection to the database is open. self.assertTrue(connection.in_atomic_block) self.expectThat(connection.connection, Not(Is(None))) function = Mock() function.__name__ = self.getUniqueString() function.side_effect = check_inner # Call `function` via the `transactional` decorator. decorated_function = orm.transactional(function) decorated_function(sentinel.arg, kwarg=sentinel.kwarg) # `function` was called -- and therefore `check_inner` too -- # and the arguments passed correctly. self.assertThat( function, MockCalledOnceWith(sentinel.arg, kwarg=sentinel.kwarg) ) # After the decorated function has returned the transaction has # been exited, and the connection has been closed. self.assertFalse(connection.in_atomic_block) self.expectThat(connection.connection, Is(None))
Example #15
Source File: base_mixins.py From drf-tracking with ISC License | 4 votes |
def finalize_response(self, request, response, *args, **kwargs): response = super(BaseLoggingMixin, self).finalize_response(request, response, *args, **kwargs) # Ensure backward compatibility for those using _should_log hook should_log = self._should_log if hasattr(self, '_should_log') else self.should_log if should_log(request, response): if response.streaming: rendered_content = None elif hasattr(response, 'rendered_content'): rendered_content = response.rendered_content else: rendered_content = response.getvalue() self.log.update( { 'remote_addr': self._get_ip_address(request), 'view': self._get_view_name(request), 'view_method': self._get_view_method(request), 'path': request.path, 'host': request.get_host(), 'method': request.method, 'query_params': self._clean_data(request.query_params.dict()), 'user': self._get_user(request), 'response_ms': self._get_response_ms(), 'response': self._clean_data(rendered_content), 'status_code': response.status_code, } ) if self._clean_data(request.query_params.dict()) == {}: self.log.update({'query_params': self.log['data']}) try: if not connection.settings_dict.get('ATOMIC_REQUESTS'): self.handle_log() else: if getattr(response, 'exception', None) and connection.in_atomic_block: # response with exception (HTTP status like: 401, 404, etc) # pointwise disable atomic block for handle log (TransactionManagementError) connection.set_rollback(True) connection.set_rollback(False) self.handle_log() except Exception: # ensure that all exceptions raised by handle_log # doesn't prevent API call to continue as expected logger.exception('Logging API call raise exception!') return response
Example #16
Source File: orm.py From maas with GNU Affero General Public License v3.0 | 4 votes |
def transactional(func): """Decorator that wraps calls to `func` in a Django-managed transaction. It ensures that connections are closed if necessary. This keeps Django happy, especially in the test suite. In addition, if `func` is being invoked from outside of a transaction, this will retry if it fails with a retryable failure. """ func_within_txn = transaction.atomic(func) # For savepoints. func_outside_txn = retry_on_retryable_failure( func_within_txn, reset=post_commit_hooks.reset ) @wraps(func) def call_within_transaction(*args, **kwargs): if connection.in_atomic_block: # Don't use the retry-capable function if we're already in a # transaction; retrying is pointless when the txn is broken. with post_commit_hooks.savepoint(): return func_within_txn(*args, **kwargs) else: # Use the retry-capable function, firing post-transaction hooks. # # If there is not yet a connection to the database, connect before # calling the decorated function, then disconnect when done. This # can be important when using non-transactional advisory locks # that may be held before, during, and/or after this transactional # block. # # Previously, close_old_connections() was used here, which would # close connections without realising that they were still in use # for non-transactional advisory locking. This had the effect of # releasing all locks prematurely: not good. # with connected(), post_commit_hooks: return func_outside_txn(*args, **kwargs) # For convenience, when introspecting for example, expose the original # function on the function we're returning. call_within_transaction.func = func return call_within_transaction