decoratorApi.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. """
  2. @author: luojunhui
  3. """
  4. import time
  5. import requests
  6. def retryOnNone():
  7. """
  8. 基于None类型数据的重试装饰器
  9. :return:
  10. """
  11. def decorator(func):
  12. """
  13. :param func:
  14. :return:
  15. """
  16. max_retries = 10
  17. wait_seconds = 2
  18. def wrapper(*args, **kwargs):
  19. """
  20. :param args:
  21. :param kwargs:
  22. :return:
  23. """
  24. for attempt in range(max_retries):
  25. response = func(*args, **kwargs)
  26. if response['data'] is not None:
  27. return response
  28. time.sleep(wait_seconds)
  29. return None
  30. return wrapper
  31. return decorator
  32. def retryOnTimeout(retries=3, delay=2):
  33. """
  34. 超时重试code
  35. :param retries:
  36. :param delay:
  37. :return:
  38. """
  39. def decorator(func):
  40. """
  41. :param func:
  42. :return:
  43. """
  44. def wrapper(*args, **kwargs):
  45. """
  46. :param args:
  47. :param kwargs:
  48. :return:
  49. """
  50. for attempt in range(retries):
  51. try:
  52. return func(*args, **kwargs)
  53. except requests.exceptions.Timeout:
  54. if attempt < retries - 1:
  55. time.sleep(delay)
  56. print(f"Timeout occurred, retrying... ({attempt + 1}/{retries})")
  57. else:
  58. print("Maximum retries reached. Function failed.")
  59. raise
  60. return wrapper
  61. return decorator