I am trying to limit the time a function is allowed to run in python (flask). It would look something like this:
def my_function:
try:
long_function_time()
catch TimeOutException:
return "Function took too long to execute"
def long_function_time:
#stuff here
I have initially tried using signals but been told thats not a good approach since flask runs in a threaded environment. I want the max execution time to be flexible, so that I easily can change it.
The code I currently use (which sometimes does not work, don't know why):
class TimedOutExc(Exception):
pass
def deadline(timeout, *args):
def decorate(f):
def handler(signum, frame):
signal.alarm(0)
raise TimedOutExc()
def new_f(*args):
signal.signal(signal.SIGALRM, handler)
signal.alarm(timeout)
return f(*args)
new_f.__name__ = f.__name__
return new_f
return decorate
Thanks in advance!