base.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import time
  2. class TimeOutError(Exception):
  3. """The operation has timed out."""
  4. class BaseBackend(object):
  5. TimeOutError = TimeOutError
  6. def __init__(self):
  7. pass
  8. def mark_as_done(self, task_id, result):
  9. raise NotImplementedError(
  10. "Backends must implement the mark_as_done method")
  11. def get_status(self, task_id):
  12. raise NotImplementedError(
  13. "Backends must implement the get_status method")
  14. def prepare_result(self, result):
  15. if result is None:
  16. return True
  17. return result
  18. def get_result(self, task_id):
  19. raise NotImplementedError(
  20. "Backends must implement the get_result method")
  21. def is_done(self, task_id):
  22. return self.get_status(task_id) == "DONE"
  23. def cleanup(self):
  24. pass
  25. def wait_for(self, task_id, timeout=None):
  26. time_start = time.time()
  27. while True:
  28. status = self.get_status(task_id)
  29. if status == "DONE":
  30. return self.get_result(task_id)
  31. if timeout and time.time() > time_start + timeout:
  32. raise self.TimeOutError(
  33. "Timed out while waiting for task %s" % (task_id))