Move RateLimiter to tfw.util

This commit is contained in:
Kristóf Tóth 2018-02-13 15:02:48 +01:00
parent 60bcb8c2b0
commit fd029dbfe7
2 changed files with 23 additions and 21 deletions

View File

@ -1,33 +1,13 @@
from time import time, sleep
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from functools import wraps
from tfw.networking.event_handlers.server_connector import ServerUplinkConnector
from tfw.util import RateLimiter
from tfw.config.logs import logging
log = logging.getLogger(__name__)
class RateLimiter:
def __init__(self, rate_per_second):
self.min_interval = 1 / float(rate_per_second)
self.last_call = time()
def __call__(self, fun):
@wraps(fun)
def wrapper(*args, **kwargs):
self._limit_rate()
fun(*args, **kwargs)
return wrapper
def _limit_rate(self): #TODO: pls review me :3
since_last_call = time() - self.last_call
to_next_call = self.min_interval - since_last_call
self.last_call = time()
if to_next_call > 0:
sleep(to_next_call)
class WebideReloadEventHandler(FileSystemEventHandler):
def __init__(self):

View File

@ -1,6 +1,8 @@
import xmlrpc.client, zmq
from contextlib import suppress
from xmlrpc.client import Fault as SupervisorFault
from time import time, sleep
from functools import wraps
from tfw.config import tfwenv
@ -31,3 +33,23 @@ class SupervisorMixin:
class ZMQConnectorBase:
def __init__(self, zmq_context=None):
self._zmq_context = zmq_context or zmq.Context.instance()
class RateLimiter:
def __init__(self, rate_per_second):
self.min_interval = 1 / float(rate_per_second)
self.last_call = time()
def __call__(self, fun):
@wraps(fun)
def wrapper(*args, **kwargs):
self._limit_rate()
fun(*args, **kwargs)
return wrapper
def _limit_rate(self): #TODO: pls review me :3
since_last_call = time() - self.last_call
to_next_call = self.min_interval - since_last_call
self.last_call = time()
if to_next_call > 0:
sleep(to_next_call)