decorators.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. # -*- coding: utf-8 -*-
  2. # Licensed under the Apache License, Version 2.0 (the "License");
  3. # you may not use this file except in compliance with the License.
  4. # You may obtain a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software
  9. # distributed under the License is distributed on an "AS IS" BASIS,
  10. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  11. # implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import time
  15. def retry(count=1, delay=0, retry_on=Exception):
  16. """
  17. Decorator which tries to run specified fuction if the previous
  18. run ended by given exception. Retry count and delays can be also
  19. specified.
  20. """
  21. if count < 0 or delay < 0:
  22. raise ValueError('Count and delay has to be positive number.')
  23. def decorator(func):
  24. def wrapper(*args, **kwargs):
  25. tried = 0
  26. while tried <= count:
  27. try:
  28. return func(*args, **kwargs)
  29. except retry_on:
  30. if tried >= count:
  31. raise
  32. if delay:
  33. time.sleep(delay)
  34. tried += 1
  35. wrapper.func_name = func.func_name
  36. return wrapper
  37. return decorator