2019-12-06 10:35:21 +02:00
|
|
|
import limits
|
|
|
|
import limits.storage
|
|
|
|
import limits.strategies
|
|
|
|
|
|
|
|
|
2020-02-09 18:38:18 +02:00
|
|
|
class LimitWrapper(object):
|
|
|
|
""" Wraps a limit by providing the storage, item and identifiers
|
|
|
|
"""
|
2019-12-06 10:35:21 +02:00
|
|
|
|
2020-02-09 18:38:18 +02:00
|
|
|
def __init__(self, limiter, limit, *identifiers):
|
|
|
|
self.limiter = limiter
|
|
|
|
self.limit = limit
|
|
|
|
self.base_identifiers = identifiers
|
|
|
|
|
|
|
|
def test(self, *args):
|
|
|
|
return self.limiter.test(self.limit, *(self.base_identifiers + args))
|
|
|
|
|
|
|
|
def hit(self, *args):
|
|
|
|
return self.limiter.hit(self.limit, *(self.base_identifiers + args))
|
|
|
|
|
|
|
|
def get_window_stats(self, *args):
|
|
|
|
return self.limiter.get_window_stats(self.limit, *(self.base_identifiers + args))
|
|
|
|
|
|
|
|
|
|
|
|
class LimitWraperFactory(object):
|
|
|
|
""" Global limiter, to be used as a factory
|
|
|
|
"""
|
2019-12-06 10:35:21 +02:00
|
|
|
|
|
|
|
def init_app(self, app):
|
|
|
|
self.storage = limits.storage.storage_from_string(app.config["RATELIMIT_STORAGE_URL"])
|
|
|
|
self.limiter = limits.strategies.MovingWindowRateLimiter(self.storage)
|
2020-02-09 18:38:18 +02:00
|
|
|
|
|
|
|
def get_limiter(self, limit, *args):
|
|
|
|
return LimitWrapper(self.limiter, limits.parse(limit), *args)
|