baseimage-tutorial-framework/lib/tfw/decorators/rate_limiter.py
2018-07-30 17:54:26 +02:00

34 lines
1011 B
Python

# Copyright (C) 2018 Avatao.com Innovative Learning Kft.
# All Rights Reserved. See LICENSE file for details.
from functools import wraps, partial
from time import time, sleep
class RateLimiter:
def __init__(self, rate_per_second, action=sleep):
self.min_interval = 1 / float(rate_per_second)
self.action = action
self.fun = None
self.last_call = time()
def __call__(self, fun):
@wraps(fun)
def wrapper(*args, **kwargs):
self.fun = partial(fun, *args, **kwargs)
limit_seconds = self._limit_rate()
if limit_seconds:
self.action(limit_seconds)
return
self.fun()
return wrapper
def _limit_rate(self):
seconds_since_last_call = time() - self.last_call
seconds_to_next_call = self.min_interval - seconds_since_last_call
self.last_call = time()
if seconds_to_next_call > 0:
return seconds_to_next_call
return 0