How to use the transaction.interfaces.TransientError function in transaction

To help you get started, we’ve selected a few transaction examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github TurboGears / tg2 / tests / test_configuration.py View on Github external
def test(self):
                self.attempts.append(True)
                if len(self.attempts) == 3:
                    return 'HI!'
                raise TransientError()
github Pylons / pyramid_tm / tests / test_it.py View on Github external
def test_handler_retryable_exception_defaults_to_1(self):
        from transaction.interfaces import TransientError
        class Conflict(TransientError):
            pass
        count = []
        def handler(request, count=count):
            raise Conflict
        self.assertRaises(Conflict, self._callFUT, handler=handler)
github zopefoundation / Zope / src / ZPublisher / WSGIPublisher.py View on Github external
exc_info = (exc_type, exc, sys.exc_info()[2])

        try:
            # Raise exception from app if handle-errors is False
            # (set by zope.testbrowser in some cases)
            if request.environ.get('x-wsgiorg.throw_errors', False):
                reraise(*exc_info)

            retry = False
            unauth = False
            debug_exc = getattr(response, 'debug_exceptions', False)

            # If the exception is transient and the request can be retried,
            # shortcut further processing. It makes no sense to have an
            # exception view registered for this type of exception.
            if isinstance(exc, TransientError) and request.supports_retry():
                retry = True
            else:
                # Handle exception view. Make sure an exception view that
                # blows up doesn't leave the user e.g. unable to log in.
                try:
                    exc_view_created = _exc_view_created_response(
                        exc, request, response)
                except Exception:
                    exc_view_created = False

                # _unauthorized modifies the response in-place. If this hook
                # is used, an exception view for Unauthorized has to merge
                # the state of the response and the exception instance.
                if isinstance(exc, Unauthorized):
                    unauth = True
                    exc.setRealm(response.realm)
github Nexedi / erp5 / product / ERP5Type / patches / WSGIPublisher.py View on Github external
raise
                    exc_view_created = False
            else:
                # Handle exception view
                exc_view_created = _exc_view_created_response(
                    exc, request, response)

                if isinstance(exc, Unauthorized):
                    # _unauthorized modifies the response in-place. If this hook
                    # is used, an exception view for Unauthorized has to merge
                    # the state of the response and the exception instance.
                    exc.setRealm(response.realm)
                    response._unauthorized()
                    response.setStatus(exc.getStatus())

                retry = isinstance(exc, TransientError) and request.supports_retry()

            notify(pubevents.PubBeforeAbort(request, exc_info, retry))
            tm.abort()
            notify(pubevents.PubFailure(request, exc_info, retry))

            if retry:
                reraise(*exc_info)

            if not (exc_view_created or isinstance(exc, Unauthorized)):
                reraise(*exc_info)
        finally:
            # Avoid traceback / exception reference cycle.
            del exc, exc_info
    finally:
        endInteraction()
github Pylons / pyramid_tm / src / pyramid_tm / __init__.py View on Github external
from pyramid.util import DottedNameResolver
import transaction
import warnings
import zope.interface

try:
    from pyramid_retry import IRetryableError
except ImportError:  # pragma: no cover
    IRetryableError = zope.interface.Interface

try:
    from pyramid_retry import mark_error_retryable
except ImportError:  # pragma: no cover
    mark_error_retryable = lambda error: None

mark_error_retryable(transaction.interfaces.TransientError)

from .compat import reraise
from .compat import text_

resolver = DottedNameResolver(None)


def default_commit_veto(request, response):
    """
    When used as a commit veto, the logic in this function will cause the
    transaction to be aborted if:

    - An ``X-Tm`` response header with the value ``abort`` (or any value
      other than ``commit``) exists.

    - The response status code starts with ``4`` or ``5``.
github Nexedi / erp5 / product / ERP5Type / patches / WSGIPublisher.py View on Github external
_request
            if _request is not None
            else _request_factory(environ['wsgi.input'],
                                  environ,
                                  new_response))

        for i in range(getattr(new_request, 'retry_max_count', 3) + 1):
            request = new_request
            response = new_response
            setRequest(request)
            try:
                with load_app(module_info) as new_mod_info:
                    with transaction_pubevents(request, response, err_hook):
                        response = _publish(request, new_mod_info)
                break
            except TransientError:
                if request.supports_retry():
                    new_request = request.retry()
                    new_response = new_request.response
                else:
                    raise
            finally:
                request.close()
                clearRequest()

        # Start the WSGI server response
        status, headers = response.finalize()
        start_response(status, headers)

        if isinstance(response.body, _FILE_TYPES) or \
           IUnboundStreamIterator.providedBy(response.body):
            result = response.body
github assembl / assembl / assembl / tweens / virtuoso_deadlock.py View on Github external
import time
import random

from transaction.interfaces import TransientError
from sqlalchemy.exc import DBAPIError

# With thanks to rkhayrov in http://stackoverflow.com/questions/18348759/


class DeadlockError(DBAPIError, TransientError):
    pass


def transient_deadlock_tween_factory(handler, registry):
    """This defines a tween that will retry a request if it failed
    thanks to a deadlock in the virtuoso database."""
    def transient_deadlock_tween(request):
        try:
            return handler(request)
        except DBAPIError as e:
            orig = e.orig
            if getattr(orig, 'args', [None])[0] == '40001':
                time.sleep(random.random())
                raise DeadlockError(e.statement, e.params, orig)
            else:
                raise
github zopefoundation / Zope / src / ZPublisher / WSGIPublisher.py View on Github external
for i in range(getattr(new_request, 'retry_max_count', 3) + 1):
            request = new_request
            response = new_response
            setRequest(request)
            try:
                with load_app(module_info) as new_mod_info:
                    with transaction_pubevents(request, response):
                        response = _publish(request, new_mod_info)

                        user = getSecurityManager().getUser()
                        if user is not None and \
                           user.getUserName() != 'Anonymous User':
                            environ['REMOTE_USER'] = user.getUserName()
                break
            except TransientError:
                if request.supports_retry():
                    request.delay_retry()  # Insert a time delay
                    new_request = request.retry()
                    new_response = new_request.response
                else:
                    raise
            finally:
                request.close()
                clearRequest()

        # Start the WSGI server response
        status, headers = response.finalize()
        start_response(status, headers)

        if isinstance(response.body, _FILE_TYPES) or \
           IUnboundStreamIterator.providedBy(response.body):