homework01.py 938 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. """
  2. 装饰器的应用
  3. """
  4. from functools import wraps
  5. from random import randint
  6. from time import sleep
  7. class Retry():
  8. """让函数可以重试执行的装饰器"""
  9. def __init__(self, times=3, max_wait=0, errors=(Exception, )):
  10. self.times = times
  11. self.max_wait = max_wait
  12. self.errors = errors
  13. def __call__(self, func):
  14. @wraps(func)
  15. def wrapper(*args, **kwargs):
  16. for _ in range(self.times):
  17. try:
  18. return func(*args, **kwargs)
  19. except self.errors:
  20. sleep(randint(self.max_wait))
  21. return wrapper
  22. def retry(*, times=3, max_wait=0, errors=(Exception, )):
  23. """让函数重试执行的装饰器函数"""
  24. def decorate(func):
  25. @wraps(func)
  26. def wrapper(*args, **kwargs):
  27. for _ in range(times):
  28. try:
  29. return func(*args, **kwargs)
  30. except errors:
  31. sleep(randint(max_wait))
  32. return wrapper
  33. return decorate
  34. # @Retry(max_wait=5)
  35. @retry(max_wait=5)
  36. def get_data_from_url(url):
  37. pass