retry.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. # Copyright 2016 Julien Danjou
  2. # Copyright 2016 Joshua Harlow
  3. # Copyright 2013-2014 Ray Holder
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import abc
  17. import re
  18. import six
  19. from tenacity import compat as _compat
  20. @six.add_metaclass(abc.ABCMeta)
  21. class retry_base(object):
  22. """Abstract base class for retry strategies."""
  23. @abc.abstractmethod
  24. def __call__(self, retry_state):
  25. pass
  26. def __and__(self, other):
  27. return retry_all(self, other)
  28. def __or__(self, other):
  29. return retry_any(self, other)
  30. class _retry_never(retry_base):
  31. """Retry strategy that never rejects any result."""
  32. def __call__(self, retry_state):
  33. return False
  34. retry_never = _retry_never()
  35. class _retry_always(retry_base):
  36. """Retry strategy that always rejects any result."""
  37. def __call__(self, retry_state):
  38. return True
  39. retry_always = _retry_always()
  40. class retry_if_exception(retry_base):
  41. """Retry strategy that retries if an exception verifies a predicate."""
  42. def __init__(self, predicate):
  43. self.predicate = predicate
  44. @_compat.retry_dunder_call_accept_old_params
  45. def __call__(self, retry_state):
  46. if retry_state.outcome.failed:
  47. return self.predicate(retry_state.outcome.exception())
  48. class retry_if_exception_type(retry_if_exception):
  49. """Retries if an exception has been raised of one or more types."""
  50. def __init__(self, exception_types=Exception):
  51. self.exception_types = exception_types
  52. super(retry_if_exception_type, self).__init__(
  53. lambda e: isinstance(e, exception_types))
  54. class retry_unless_exception_type(retry_if_exception):
  55. """Retries until an exception is raised of one or more types."""
  56. def __init__(self, exception_types=Exception):
  57. self.exception_types = exception_types
  58. super(retry_unless_exception_type, self).__init__(
  59. lambda e: not isinstance(e, exception_types))
  60. @_compat.retry_dunder_call_accept_old_params
  61. def __call__(self, retry_state):
  62. # always retry if no exception was raised
  63. if not retry_state.outcome.failed:
  64. return True
  65. return self.predicate(retry_state.outcome.exception())
  66. class retry_if_result(retry_base):
  67. """Retries if the result verifies a predicate."""
  68. def __init__(self, predicate):
  69. self.predicate = predicate
  70. @_compat.retry_dunder_call_accept_old_params
  71. def __call__(self, retry_state):
  72. if not retry_state.outcome.failed:
  73. return self.predicate(retry_state.outcome.result())
  74. class retry_if_not_result(retry_base):
  75. """Retries if the result refutes a predicate."""
  76. def __init__(self, predicate):
  77. self.predicate = predicate
  78. @_compat.retry_dunder_call_accept_old_params
  79. def __call__(self, retry_state):
  80. if not retry_state.outcome.failed:
  81. return not self.predicate(retry_state.outcome.result())
  82. class retry_if_exception_message(retry_if_exception):
  83. """Retries if an exception message equals or matches."""
  84. def __init__(self, message=None, match=None):
  85. if message and match:
  86. raise TypeError(
  87. "{}() takes either 'message' or 'match', not both".format(
  88. self.__class__.__name__))
  89. # set predicate
  90. if message:
  91. def message_fnc(exception):
  92. return message == str(exception)
  93. predicate = message_fnc
  94. elif match:
  95. prog = re.compile(match)
  96. def match_fnc(exception):
  97. return prog.match(str(exception))
  98. predicate = match_fnc
  99. else:
  100. raise TypeError(
  101. "{}() missing 1 required argument 'message' or 'match'".
  102. format(self.__class__.__name__))
  103. super(retry_if_exception_message, self).__init__(predicate)
  104. class retry_if_not_exception_message(retry_if_exception_message):
  105. """Retries until an exception message equals or matches."""
  106. def __init__(self, *args, **kwargs):
  107. super(retry_if_not_exception_message, self).__init__(*args, **kwargs)
  108. # invert predicate
  109. if_predicate = self.predicate
  110. self.predicate = lambda *args_, **kwargs_: not if_predicate(
  111. *args_, **kwargs_)
  112. @_compat.retry_dunder_call_accept_old_params
  113. def __call__(self, retry_state):
  114. if not retry_state.outcome.failed:
  115. return True
  116. return self.predicate(retry_state.outcome.exception())
  117. class retry_any(retry_base):
  118. """Retries if any of the retries condition is valid."""
  119. def __init__(self, *retries):
  120. self.retries = tuple(_compat.retry_func_accept_retry_state(r)
  121. for r in retries)
  122. @_compat.retry_dunder_call_accept_old_params
  123. def __call__(self, retry_state):
  124. return any(r(retry_state) for r in self.retries)
  125. class retry_all(retry_base):
  126. """Retries if all the retries condition are valid."""
  127. def __init__(self, *retries):
  128. self.retries = tuple(_compat.retry_func_accept_retry_state(r)
  129. for r in retries)
  130. @_compat.retry_dunder_call_accept_old_params
  131. def __call__(self, retry_state):
  132. return all(r(retry_state) for r in self.retries)