tornadoweb.py 1.7 KB

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