from dave.config import redis
def ratelimit(fun, userhost):
"""
Ratelimit a function
:param fun: Function to ratelimit
:param userhost: Host of the user
:return: True, if this function is allowed to be executed
"""
if not hasattr(fun, "ratelimit"):
return True
value = fun.ratelimit["value"]
per = fun.ratelimit["per"]
key = "ratelimit:{}:{}:{}".format(userhost, fun.__module__, fun.__qualname__)
if not redis.exists(key):
redis.setex(key, per, 0)
elif int(redis.get(key)) >= value:
return False
redis.incr(key)
return True