public
Last active

Decorator for timing out a method that returns a twisted deferred.

  • Download Gist
twisted_timeout.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.