Advertisement
Guest User

Untitled

a guest
Nov 30th, 2015
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.00 KB | None | 0 0
  1. import functools
  2. import itertools
  3. import logging
  4. import time
  5.  
  6.  
  7. log = logging.getLogger(__name__)
  8.  
  9.  
  10. def retry(times, timeout=0.2, exceptions=None):
  11. """A retry decorator.
  12.  
  13. :param times: integer number of times to retry
  14. :param timeout: floating point number of second to wait between calls
  15. :param exceptions: tuple of exceptions to retry on. defaults to all
  16. """
  17. if exceptions is None:
  18. exceptions = (Exception,)
  19. else:
  20. exceptions = tuple(exceptions)
  21.  
  22. def wrapper(fn):
  23. @functools.wraps(fn)
  24. def decorated(*args, **kwargs):
  25. for attempt in itertools.count(1):
  26. log.debug("Calling function '%s' attempt '%s'",
  27. fn.__name__, attempt)
  28. try:
  29. return fn(*args, **kwargs)
  30. except exceptions:
  31. if attempt > times:
  32. raise
  33. if timeout:
  34. time.sleep(timeout)
  35. return decorated
  36. return wrapper
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement