Created
December 10, 2010 00:12
-
-
Save theduderog/735556 to your computer and use it in GitHub Desktop.
A decorator for adding timeouts to Deferred calls that don't offer an alternative
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# This gist is released under Creative Commons Public Domain Dedication License CC0 1.0 | |
# http://creativecommons.org/publicdomain/zero/1.0/ | |
# | |
from twisted.internet import defer, reactor | |
class TimeoutError(Exception): | |
"""Raised when time expires in timeout decorator""" | |
def timeout(secs): | |
""" | |
Decorator to add timeout to Deferred calls | |
""" | |
def wrap(func): | |
@defer.inlineCallbacks | |
def _timeout(*args, **kwargs): | |
rawD = func(*args, **kwargs) | |
if not isinstance(rawD, defer.Deferred): | |
defer.returnValue(rawD) | |
timeoutD = defer.Deferred() | |
timesUp = reactor.callLater(secs, timeoutD.callback, None) | |
try: | |
rawResult, timeoutResult = yield defer.DeferredList([rawD, timeoutD], fireOnOneCallback=True, fireOnOneErrback=True, consumeErrors=True) | |
except defer.FirstError, e: | |
#Only rawD should raise an exception | |
assert e.index == 0 | |
timesUp.cancel() | |
e.subFailure.raiseException() | |
else: | |
#Timeout | |
if timeoutD.called: | |
rawD.cancel() | |
raise TimeoutError("%s secs have expired" % secs) | |
#No timeout | |
timesUp.cancel() | |
defer.returnValue(rawResult) | |
return _timeout | |
return wrap |
Hi Roger,
Thanks a lot for your explanation.
Regards,
Yong
Roger, can you clarify the copyright/license for this code? Thanks.
It's public domain. I do not wish to retain any copyrights. What's the best way to indicate that?
Roger,
CC0 is intended to allow one to place a work as nearly as possible into the public domain, worldwide. I believe that it would be sufficient to add a comment along the lines of:
"This gist is released under the Creative Commons 0 license. See http://creativecommons.org/publicdomain/zero/1.0/ for more information"
I appreciate it.
Thanks @htoothrot
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Your test function needs to return a Deferred, instead of calling sleep().
Here's the whole thing: