On 14/02/2015, at 11:01 PM, Paul Royik <[email protected]> wrote:
> Thank you for all your help and time. You really helped me a lot.
> As a final note, I think that func.info.end_time = time.time() + seconds
> should be written outside wrapper, because end_time will be rewritten each
> time func is called (there is some recursion inside my algo), but overall
> this approach works perfectly.
>
> import functools
>
> def time_limit(seconds):
> def decorator(func):
> func.info = threading.local()
> func.info.end_time = time.time() + seconds
>
> def check_timeout():
> if time.time() > func.info.end_time:
> raise TimeoutException
>
> func.check_timeout = check_timeout
>
> @functools.wraps(func)
> def wrapper(*args, **kwargs):
> return func(*args, **kwargs)
>
> return wrapper
>
> return decorator
You can't do that.
That will set the end time from the time the that Python module where the
decorator was used was imported. The end time would only be set for the thread
which imported the module originally.
If has to be on the call of the function.
If your function is recursive, then it is going to need to be a bit tricker.
At a guess, untested, something like:
import functools
def time_limit(seconds):
def decorator(func):
func.info = threading.local()
func.info.counter = 0
def check_timeout():
if time.time() > func.info.end_time:
raise TimeoutException
func.check_timeout = check_timeout
@functools.wraps(func)
def wrapper(*args, **kwargs):
if func.info.counter == 0:
func.info.end_time = time.time() + seconds
func.info.counter += 1
try:
return func(*args, **kwargs)
finally:
func.info.counter -= 1
return wrapper
return decorator
--
You received this message because you are subscribed to the Google Groups
"modwsgi" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/modwsgi.
For more options, visit https://groups.google.com/d/optout.