_asyncio.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2016 Étienne Bersac
  3. # Copyright 2016 Julien Danjou
  4. # Copyright 2016 Joshua Harlow
  5. # Copyright 2013-2014 Ray Holder
  6. #
  7. # Licensed under the Apache License, Version 2.0 (the "License");
  8. # you may not use this file except in compliance with the License.
  9. # You may obtain a copy of the License at
  10. #
  11. # http://www.apache.org/licenses/LICENSE-2.0
  12. #
  13. # Unless required by applicable law or agreed to in writing, software
  14. # distributed under the License is distributed on an "AS IS" BASIS,
  15. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. # See the License for the specific language governing permissions and
  17. # limitations under the License.
  18. import asyncio
  19. import sys
  20. from tenacity import BaseRetrying
  21. from tenacity import DoAttempt
  22. from tenacity import DoSleep
  23. from tenacity import RetryCallState
  24. class AsyncRetrying(BaseRetrying):
  25. def __init__(self,
  26. sleep=asyncio.sleep,
  27. **kwargs):
  28. super(AsyncRetrying, self).__init__(**kwargs)
  29. self.sleep = sleep
  30. @asyncio.coroutine
  31. def call(self, fn, *args, **kwargs):
  32. self.begin(fn)
  33. retry_state = RetryCallState(
  34. retry_object=self, fn=fn, args=args, kwargs=kwargs)
  35. while True:
  36. do = self.iter(retry_state=retry_state)
  37. if isinstance(do, DoAttempt):
  38. try:
  39. result = yield from fn(*args, **kwargs)
  40. except BaseException:
  41. retry_state.set_exception(sys.exc_info())
  42. else:
  43. retry_state.set_result(result)
  44. elif isinstance(do, DoSleep):
  45. retry_state.prepare_for_next_attempt()
  46. yield from self.sleep(do)
  47. else:
  48. return do