Skip to content

Instantly share code, notes, and snippets.

@jhorman
Created March 29, 2011 02:35
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jhorman/891714 to your computer and use it in GitHub Desktop.
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):
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
d = method(self, *args, **kwargs)
def on_timeout():
if not d.called:
if error_type:
d.errback(error_type(error_message))
d.cancel()
reactor.callLater(seconds, on_timeout)
return d
return wrapper
return attach_timeout
# Example
@timeout(20, ExternalStorageException, 'cassandra fetch timeout')
@defer.inlineCallbacks
def cass_get(self, key, column_family):
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment