Decorator retries a function when expected exceptions are raised.
10142
def retryable_transaction(attempts=3, exceptions=(OperationalError,)):
    """"""
    assert len(exceptions) > 0
    assert attempts > 0

    def wrapper(f):
        @functools.wraps(f)
        def wrapped(*args, **kwargs):
            for i in xrange(attempts):
                try:
                    return f(*args, **kwargs)
                except exceptions, e:
                    if i == (attempts - 1):
                        raise
                    logging.warning(
                        'Retryable error in transaction on attempt %d. %s: %s',
                        i + 1, e.__class__.__name__, e)
                    db.session.rollback()

        return wrapped

    return wrapper
335008
def retry(*dargs, **dkw):
    
    # support both @retry and @retry() as valid syntax
    if len(dargs) == 1 and callable(dargs[0]):
        def wrap_simple(f):

            @six.wraps(f)
            def wrapped_f(*args, **kw):
                return Retrying().call(f, *args, **kw)

            return wrapped_f

        return wrap_simple(dargs[0])

    else:
        def wrap(f):

            @six.wraps(f)
            def wrapped_f(*args, **kw):
                return Retrying(*dargs, **dkw).call(f, *args, **kw)

            return wrapped_f

        return wrap
20067
def _check_decorator(fct):
        """"""
        def wrapper(self, *args, **kw):
            if self.is_enable():
                ret = fct(self, *args, **kw)
            else:
                ret = self.stats
            return ret
        return wrapper
961356
def retry_on_exception(num_retries, base_delay=0, exc_type=Exception):
    
    def _retry_on_exception_inner_1(f):
        def _retry_on_exception_inner_2(*args, **kwargs):
            retries = num_retries
            multiplier = 1
            while True:
                try:
                    return f(*args, **kwargs)
                except exc_type:
                    if not retries:
                        raise

                delay = base_delay * multiplier
                multiplier += 1
                log("Retrying '%s' %d more times (delay=%s)" %
                    (f.__name__, retries, delay), level=INFO)
                retries -= 1
                if delay:
                    time.sleep(delay)

        return _retry_on_exception_inner_2

    return _retry_on_exception_inner_1
137807
def retry(retries=KAFKA_WAIT_RETRIES, delay=KAFKA_WAIT_INTERVAL,
          check_exceptions=()):
    """"""
    def decorator(func):
        """Decorator."""
        def f_retry(*args, **kwargs):
            """Retry running function on exception after delay."""
            for i in range(1, retries + 1):
                try:
                    return func(*args, **kwargs)
                # pylint: disable=W0703
                # We want to catch all exceptions here to retry.
                except check_exceptions + (Exception,) as exc:
                    if i < retries:
                        logger.info('Connection attempt %d of %d failed',
                                    i, retries)
                        if isinstance(exc, check_exceptions):
                            logger.debug('Caught known exception, retrying...',
                                         exc_info=True)
                        else:
                            logger.warn(
                                'Caught unknown exception, retrying...',
                                exc_info=True)
                    else:
                        logger.exception('Failed after %d attempts', retries)

                        raise

                # No exception so wait before retrying
                time.sleep(delay)

        return f_retry
    return decorator
612893
def retry(retry_count):
    

    def func(f):
        @functools.wraps(f)
        def wrapper(*args, **kwargs):
            for backoff in range(retry_count):
                try:
                    return f(*args, **kwargs)
                except Exception:
                    time.sleep(2 ** backoff)
            else:
                raise SbgError('{}: failed to complete: {}'.format(
                    threading.current_thread().getName(), f.__name__)
                )

        return wrapper

    return func
658626
def catches(exc, handler=re_raise):
    '''
    
    '''
    if not __CHECKING__:
        return lambda f: f

    def wrap(f):
        def call(*args, **kwd):
            try:
                ID = exc_checker.set_attention(exc)
                res = f(*args, **kwd)
                exc_checker.remove_attention(exc, ID)
                return res
            # handle checked exception
            except exc, e:
                exc_checker.remove_attention(exc, ID)
                traceback = sys.exc_info()[2]
                return handler(exc, str(e), traceback.tb_next.tb_next)
            # re-raise unchecked exception but remove checked exeption info first
            except Exception, e:
                exc_checker.remove_attention(exc, ID)
                traceback = sys.exc_info()[2]
                raise e.__class__, e.args, traceback.tb_next.tb_next
        call.__name__ = f.__name__
        return call
    return wrap
628359
def capture_exception(fn):
    """"""
    def wrapped(*args):
        try:
            return fn(*args)
        except Exception as e:
            return e
    return wrapped
842988
def transaction_retry(max_retries=1):
    
    def _outer(fun):

        @wraps(fun)
        def _inner(*args, **kwargs):
            _max_retries = kwargs.pop('exception_retry_count', max_retries)
            for retries in count(0):
                try:
                    return fun(*args, **kwargs)
                except Exception:   # pragma: no cover
                    # Depending on the database backend used we can experience
                    # various exceptions. E.g. psycopg2 raises an exception
                    # if some operation breaks the transaction, so saving
                    # the task result won't be possible until we rollback
                    # the transaction.
                    if retries >= _max_retries:
                        raise
                    try:
                        rollback_unless_managed()
                    except Exception:
                        pass
        return _inner

    return _outer
460546
def _repeat(func):
    """"""
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        """Repeats the call until True is returned."""
        ret = None
        while ret is None:
            ret = func(*args, **kwargs)
        return ret
    return wrapper
328872
def retryable(fn, protocol=None):
    
    def wrapper(self, *args, **kwargs):
        pool = self._choose_pool(protocol)

        def thunk(transport):
            return fn(self, transport, *args, **kwargs)

        return self._with_retries(pool, thunk)

    wrapper.__doc__ = fn.__doc__
    wrapper.__repr__ = fn.__repr__

    return wrapper
533334
def retry(max_retries=1):
    

    def retry_func(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            num_retries = 0
            while num_retries <= max_retries:
                try:
                    ret = func(*args, **kwargs)
                    break
                except HTTPError:
                    if num_retries == max_retries:
                        raise
                    num_retries += 1
                    time.sleep(5)
            return ret

        return wrapper

    return retry_func
1183510
def retry_on_bad_auth(func):
    """"""
    @wraps(func)
    def retry_version(self, *args, **kwargs):
        while True:
            try:
                return func(self, *args, **kwargs)
            except trolly.ResourceUnavailable:
                sys.stderr.write('bad request (refresh board id)\n')
                self._board_id = None
                self.save_key('board_id', None)
            except trolly.Unauthorised:
                sys.stderr.write('bad permissions (refresh token)\n')
                self._client = None
                self._token = None
                self.save_key('token', None)
    return retry_version
52574
def _eintr_retry(func, *args):
    """"""
    while True:
        try:
            return func(*args)
        except (OSError, select.error) as e:
            if e.args[0] != errno.EINTR:
                raise
533650
def RaiseIfNotErrorSuccess(result, func = None, arguments = ()):
    
    if result != ERROR_SUCCESS:
        raise ctypes.WinError(result)
    return result
751527
def error_wrap(func):
    """"""
    def f(*args, **kw):
        code = func(*args, **kw)
        check_error(code, context="client")
    return f
981006
def return_false_on_exception(func):
    
    @wraps(func)
    def exceptfalse(*args, **kwargs):
        if not kwargs.pop('raise_exceptions', False):
            try:
                return func(*args, **kwargs)
            except Exception:
                return False
        else:
            return func(*args, **kwargs)
    return exceptfalse