Create a gist now

Instantly share code, notes, and snippets.

Decorator for timing out a method that returns a twisted deferred.
def timeout(seconds=5, error_type=None, error_message=None):
Attaches a timeout to the deferred returned by the wrapped function.
After timeout seconds the deferred is canceled and an exception raised.
def attach_timeout(method):
def wrapper(self, *args, **kwargs):
d = method(self, *args, **kwargs)
def on_timeout():
if not d.called:
if error_type:
reactor.callLater(seconds, on_timeout)
return d
return wrapper
return attach_timeout
# Example
@timeout(20, ExternalStorageException, 'cassandra fetch timeout')
def cass_get(self, key, column_family):
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment