I have the following timeout creation decorator function:
class TimeoutError(Exception): pass
def timeout(seconds, error_message = 'Function call timed out'):
def decorated(func):
print "timeout: \t" + func.__name__
def _handle_timeout(signum, frame):
raise TimeoutError(error_message)
def wrapper(*args, **kwargs):
signal.signal(signal.SIGALRM, _handle_timeout)
signal.alarm(seconds)
try:
print "timeout wrapper: \t" + func.__name__
result = func(*args, **kwargs)
finally:
signal.alarm(0)
return result
return functools.wraps(func)(wrapper)
return decorated
And another decorator:
import inspect
class withHostAndToken(object):
__name__ = "withHostAndToken"
__doc__ = "Get the Host and Token for the API call"
def __init__(self, func):
print "withHostAndToken: \t" + func.__name__
self.func = func
self.HOST = ''
self.TOKEN = ''
def __call__(self,*args, **kwds):
if self.HOST == '':
self.HOST = "HOST"
if self.TOKEN == '':
self.TOKEN = "TOKEN"
argsspec = inspect.getargspec(self.func)
function_args = argsspec[0]
if 'HOST' in function_args:
if 'TOKEN' in function_args:
return self.func(self.HOST , self.TOKEN , *args, **kwds)
else:
return self.func(self.HOST , *args, **kwds)
elif 'TOKEN' in function_args:
return self.func(self.TOKEN, *args, **kwds)
When I try to apply both to a function I don;t get the function code to be called:
@timeout(2)
@withHostAndToken
def testDecorators():
print __name__
while True:
print '.'
testDecorators()
the output of this is:
withHostAndToken: testDecorators
timeout: withHostAndToken
timeout wrapper: withHostAndTokenProcess finished with exit code 0