Guest User

Untitled

a guest
Jul 16th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. from twisted.internet import defer, reactor
  2.  
  3. class TimeoutError(Exception):
  4. """Raised when time expires in timeout decorator"""
  5.  
  6. def timeout(secs):
  7. """
  8. Decorator to add timeout to Deferred calls
  9. """
  10. def wrap(func):
  11. @defer.inlineCallbacks
  12. def _timeout(*args, **kwargs):
  13. rawD = func(*args, **kwargs)
  14. if not isinstance(rawD, defer.Deferred):
  15. defer.returnValue(rawD)
  16.  
  17. timeoutD = defer.Deferred()
  18. timesUp = reactor.callLater(secs, timeoutD.callback, None)
  19.  
  20. try:
  21. rawResult, timeoutResult = yield defer.DeferredList([rawD, timeoutD], fireOnOneCallback=True, fireOnOneErrback=True, consumeErrors=True)
  22. except defer.FirstError, e:
  23. #Only rawD should raise an exception
  24. assert e.index == 0
  25. timesUp.cancel()
  26. e.subFailure.raiseException()
  27. else:
  28. #Timeout
  29. if timeoutD.called:
  30. rawD.cancel()
  31. raise TimeoutError("%s secs have expired" % secs)
  32.  
  33. #No timeout
  34. timesUp.cancel()
  35. defer.returnValue(rawResult)
  36. return _timeout
  37. return wrap
Add Comment
Please, Sign In to add comment