2018-04-03 12:49:14 +00:00
|
|
|
# Copyright (C) 2018 Avatao.com Innovative Learning Kft.
|
|
|
|
# All Rights Reserved. See LICENSE file for details.
|
|
|
|
|
2018-07-30 15:54:26 +00:00
|
|
|
from functools import wraps, partial
|
2018-02-13 16:56:01 +00:00
|
|
|
from time import time, sleep
|
|
|
|
|
|
|
|
|
|
|
|
class RateLimiter:
|
2018-07-30 15:54:26 +00:00
|
|
|
def __init__(self, rate_per_second, action=sleep):
|
2018-02-13 16:56:01 +00:00
|
|
|
self.min_interval = 1 / float(rate_per_second)
|
2018-07-30 15:54:26 +00:00
|
|
|
self.action = action
|
|
|
|
self.fun = None
|
2018-02-13 16:56:01 +00:00
|
|
|
self.last_call = time()
|
|
|
|
|
|
|
|
def __call__(self, fun):
|
|
|
|
@wraps(fun)
|
|
|
|
def wrapper(*args, **kwargs):
|
2018-07-30 15:54:26 +00:00
|
|
|
self.fun = partial(fun, *args, **kwargs)
|
|
|
|
limit_seconds = self._limit_rate()
|
|
|
|
if limit_seconds:
|
|
|
|
self.action(limit_seconds)
|
|
|
|
return
|
|
|
|
self.fun()
|
2018-02-13 16:56:01 +00:00
|
|
|
return wrapper
|
|
|
|
|
|
|
|
def _limit_rate(self):
|
2018-07-30 15:54:26 +00:00
|
|
|
seconds_since_last_call = time() - self.last_call
|
|
|
|
seconds_to_next_call = self.min_interval - seconds_since_last_call
|
2018-02-13 16:56:01 +00:00
|
|
|
self.last_call = time()
|
2018-07-30 15:54:26 +00:00
|
|
|
|
|
|
|
if seconds_to_next_call > 0:
|
|
|
|
return seconds_to_next_call
|
|
|
|
return 0
|