mirror of
https://github.com/avatao-content/baseimage-tutorial-framework
synced 2024-11-22 19:31:33 +00:00
Move RateLimiter to decorators
This commit is contained in:
parent
14f3a4a153
commit
b9e41c01cf
1
lib/tfw/components/decorators/__init__.py
Normal file
1
lib/tfw/components/decorators/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
from .rate_limiter import RateLimiter
|
22
lib/tfw/components/decorators/rate_limiter.py
Normal file
22
lib/tfw/components/decorators/rate_limiter.py
Normal file
@ -0,0 +1,22 @@
|
||||
from functools import wraps
|
||||
from time import time, sleep
|
||||
|
||||
|
||||
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):
|
||||
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)
|
@ -2,13 +2,12 @@ from watchdog.observers import Observer
|
||||
from watchdog.events import FileSystemEventHandler
|
||||
|
||||
from tfw.networking.event_handlers.server_connector import ServerUplinkConnector
|
||||
from tfw.util import RateLimiter
|
||||
from tfw.components.decorators import RateLimiter
|
||||
|
||||
from tfw.config.logs import logging
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
|
||||
class WebideReloadEventHandler(FileSystemEventHandler):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
@ -1,7 +1,3 @@
|
||||
from time import time, sleep
|
||||
from functools import wraps
|
||||
|
||||
|
||||
def create_source_code_response_data(filename, content, language):
|
||||
return {
|
||||
'filename': filename,
|
||||
@ -10,21 +6,3 @@ def create_source_code_response_data(filename, content, language):
|
||||
}
|
||||
|
||||
|
||||
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):
|
||||
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)
|
Loading…
Reference in New Issue
Block a user