当前位置: 首页>>代码示例>>Python>>正文


Python connection.in_atomic_block方法代码示例

本文整理汇总了Python中django.db.connection.in_atomic_block方法的典型用法代码示例。如果您正苦于以下问题:Python connection.in_atomic_block方法的具体用法?Python connection.in_atomic_block怎么用?Python connection.in_atomic_block使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.db.connection的用法示例。


在下文中一共展示了connection.in_atomic_block方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: close_connection

# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import in_atomic_block [as 别名]
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() 
开发者ID:hacktoolkit,项目名称:django-htk,代码行数:19,代码来源:db.py

示例2: savepoint

# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import in_atomic_block [as 别名]
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."
        ) 
开发者ID:maas,项目名称:maas,代码行数:26,代码来源:orm.py

示例3: _setUp

# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import in_atomic_block [as 别名]
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) 
开发者ID:maas,项目名称:maas,代码行数:25,代码来源:fixtures.py

示例4: run_once

# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import in_atomic_block [as 别名]
def run_once(self, exclude_ids=[]):
        assert not connection.in_atomic_block
        return self._run_once(exclude_ids=exclude_ids) 
开发者ID:gavinwahl,项目名称:django-postgres-queue,代码行数:5,代码来源:queue.py

示例5: test_creates_an_atomic

# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import in_atomic_block [as 别名]
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 
开发者ID:adamchainz,项目名称:django-mysql,代码行数:10,代码来源:test_locks.py

示例6: set_rollback

# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import in_atomic_block [as 别名]
def set_rollback():
    atomic_requests = connection.settings_dict.get('ATOMIC_REQUESTS', False)
    if atomic_requests and connection.in_atomic_block:
        transaction.set_rollback(True) 
开发者ID:BeanWei,项目名称:Dailyfresh-B2C,代码行数:6,代码来源:views.py

示例7: in_transaction

# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import in_atomic_block [as 别名]
def in_transaction(request):
    return HttpResponse(str(connection.in_atomic_block)) 
开发者ID:nesdis,项目名称:djongo,代码行数:4,代码来源:views.py

示例8: not_in_transaction

# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import in_atomic_block [as 别名]
def not_in_transaction(request):
    return HttpResponse(str(connection.in_atomic_block)) 
开发者ID:nesdis,项目名称:djongo,代码行数:4,代码来源:views.py

示例9: set_rollback

# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import in_atomic_block [as 别名]
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 
开发者ID:erigones,项目名称:esdc-ce,代码行数:17,代码来源:compat.py

示例10: __enter__

# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import in_atomic_block [as 别名]
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) 
开发者ID:maas,项目名称:maas,代码行数:11,代码来源:dblocks.py

示例11: in_transaction

# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import in_atomic_block [as 别名]
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 
开发者ID:maas,项目名称:maas,代码行数:14,代码来源:orm.py

示例12: test_calls_function_within_transaction_then_closes_connections

# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import in_atomic_block [as 别名]
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)) 
开发者ID:maas,项目名称:maas,代码行数:35,代码来源:test_orm.py

示例13: finalize_response

# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import in_atomic_block [as 别名]
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 
开发者ID:aschn,项目名称:drf-tracking,代码行数:49,代码来源:base_mixins.py

示例14: transactional

# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import in_atomic_block [as 别名]
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 
开发者ID:maas,项目名称:maas,代码行数:45,代码来源:orm.py


注:本文中的django.db.connection.in_atomic_block方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。