rodrigosantosbr

[Py] Retry decorator

Feb 20th, 2019
348
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.39 KB | None | 0 0
  1. import time
  2. import itertools
  3.  
  4. # tested with https://www.onlinegdb.com/online_python_compiler
  5.  
  6. def retry(delays=(0, 1, 5, 30, 60), exception=Exception):
  7.     """Repeats a function until the timeout, fail (Exception) or success
  8.        the first retry is done immediately (after 0 seconds),
  9.        the next retry after 1 second,
  10.        the next after 5 seconds,
  11.        then 30 seconds,
  12.        then 1 minute,
  13.  
  14.    Parameters
  15.    ----------
  16.        delays: list
  17.            time in seconds between retries.
  18.        exception: Exception
  19.            exception to monitor
  20.  
  21.    Returns
  22.    -------
  23.        None
  24.  
  25.    Raises
  26.    ------
  27.        Exception
  28.  
  29.    Examples
  30.    --------
  31.        >>> @retry()
  32.        >>> def divisaoPorZero(): return 1 / 0
  33.        >>> divisaoPorZero()
  34.        Tentativa de executar a operação: division by zero -- nova tentativa em 0 segundos.                                            
  35.        Tentativa de executar a operação: division by zero -- nova tentativa em 1 segundos.                                            
  36.        Tentativa de executar a operação: division by zero -- nova tentativa em 5 segundos.                                            
  37.        Tentativa de executar a operação: division by zero -- nova tentativa em 30 segundos.                                            
  38.  
  39.        Tentativa de executar a operação: [ZeroDivisionError('division by zero',)]
  40.            -- nova tentativa em 1 segundos.
  41.        Tentativa de executar a operação: [ZeroDivisionError('division by zero',)]
  42.            -- nova tentativa em 5 segundos.
  43.  
  44.    See Also
  45.    --------
  46.        http://code.activestate.com/recipes/580745-retry-decorator-in-python/?in=lang-python
  47.    """
  48.  
  49.     def wrapper(function):
  50.         def wrapped(*args, **kwargs):
  51.             for delay in itertools.chain(delays, [ None ]):
  52.                 try:
  53.                     return function(*args, **kwargs)
  54.                 except exception as e:
  55.                     if delay is None:
  56.                         print("Tentativa de executar a operação: {}.\n".format(e))
  57.                     else:
  58.                         print("Tentativa de executar a operação: {} -- nova tentativa em {} segundos.\n".format(e,delay))
  59.                         time.sleep(delay)
  60.         return wrapped
  61.     return wrapper
  62.  
  63. @retry()
  64. def divisaoPorZero():
  65.     return 1 / 0
  66.  
  67. divisaoPorZero()
Advertisement
Add Comment
Please, Sign In to add comment