On 15/02/2015, at 8:28 AM, Paul Royik <[email protected]> wrote:
> 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: # this line raises error when I
> access page second time, even on localhost.
> 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
Use this instead.
import time
import functools
import threading
def time_limit(seconds):
def decorator(func):
func.info = threading.local()
def check_timeout():
if time.time() > func.info.end_time:
raise RuntimeError('timeout')
func.check_timeout = check_timeout
@functools.wraps(func)
def wrapper(*args, **kwargs):
if not hasattr(func.info, 'counter'):
func.info.counter = 0
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
Okay, yes there will be a problem as the counter needs to be initialised per
thread.
Graham
--
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.