Created
March 29, 2011 02:35
-
-
Save jhorman/891714 to your computer and use it in GitHub Desktop.
Decorator for timing out a method that returns a twisted deferred.
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
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