def is_rate_limited(self): if not self.rate: return (None, (None, None, None)) count, seconds = parse_rate(self.rate) redis_key = f"[{self.key}][{self.value}][{count}/{seconds}]" r = redis.Redis(**self.pool) current = r.get(redis_key) if current: current = int(current.decode("utf-8")) if current >= count: return ( True, (count, count - (current if current else 0), calc_ttl(r.ttl(redis_key))), ) value = r.incr(redis_key) if value == 1: r.expire(redis_key, seconds) return (False, (count, count - (current if current else 0), calc_ttl(r.ttl(redis_key))))
def test_rate_parsing(self): tests = ( ('100/s', (100, 1)), ('100/10s', (100, 10)), ('100/m', (100, 60)), ('400/10m', (400, 10 * 60)), ('600/h', (600, 60 * 60)), ('800/d', (800, 24 * 60 * 60)), ) for input, output in tests: assert output == parse_rate(input)
def is_rate_limited(request, rate=None): if not rate: return False count, seconds = parse_rate(rate) redis_key = build_redis_key(request, count, seconds) r = redis_connection() current = r.incr(redis_key) ttl = r.ttl(redis_key) if ttl == None or ttl == -1: r.expire(redis_key, seconds) return current > count
def is_rate_limited(request, rate=None): if not rate: return False count, seconds = parse_rate(rate) redis_key = build_redis_key(request, count, seconds) r = redis_connection() current = r.get(redis_key) if current: current = int(current.decode('utf-8')) if current >= count: return True r.incr(redis_key) if r.ttl(redis_key) is None: r.expire(redis_key, seconds) return False