From ee7adb10be8397809c8a4e1859f8344fc628ec61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krist=C3=B3f=20T=C3=B3th?= Date: Mon, 30 Jul 2018 18:04:24 +0200 Subject: [PATCH] Refactor AsyncRateLimiter for ease of use (IOLoop passing) --- lib/tfw/decorators/rate_limiter.py | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/lib/tfw/decorators/rate_limiter.py b/lib/tfw/decorators/rate_limiter.py index 6fb020a..fdfa992 100644 --- a/lib/tfw/decorators/rate_limiter.py +++ b/lib/tfw/decorators/rate_limiter.py @@ -4,6 +4,8 @@ from functools import wraps, partial from time import time, sleep +from tfw.decorators.lazy_property import lazy_property + class RateLimiter: def __init__(self, rate_per_second, action=sleep): @@ -34,19 +36,25 @@ class RateLimiter: class AsyncRateLimiter(RateLimiter): - def __init__(self, rate_per_second, ioloop): - self.ioloop = ioloop - self.last_callback = None + def __init__(self, rate_per_second, ioloop_factory): + self._ioloop_factory = ioloop_factory + self._ioloop = None + self._last_callback = None + super().__init__( rate_per_second=rate_per_second, action=self.async_action ) - def async_action(self, seconds_to_next_call): - if self.last_callback: - self.ioloop.remove_timeout(self.last_callback) + @lazy_property + def ioloop(self): + return self._ioloop_factory() - self.last_callback = self.ioloop.call_later( + def async_action(self, seconds_to_next_call): + if self._last_callback: + self.ioloop.remove_timeout(self._last_callback) + + self._last_callback = self.ioloop.call_later( seconds_to_next_call, self.fun )