2017-04-22 03:06:19 +02:00
|
|
|
import urlparse
|
|
|
|
from limits.storage import Storage
|
|
|
|
from redislite import Redis
|
2017-04-22 10:28:31 +02:00
|
|
|
import time
|
2017-04-22 03:06:19 +02:00
|
|
|
|
|
|
|
class LimitsRedisLite(Storage): # For Python Limits
|
|
|
|
STORAGE_SCHEME = "redislite"
|
|
|
|
def __init__(self, uri, **options):
|
|
|
|
self.redis_instance = Redis(urlparse.urlparse(uri).netloc)
|
|
|
|
|
|
|
|
def check(self):
|
|
|
|
return True
|
|
|
|
|
|
|
|
def get_expiry(self, key):
|
2017-04-22 10:46:35 +02:00
|
|
|
return (self.redis_instance.ttl(key) or 0) + time.time()
|
2017-04-22 03:06:19 +02:00
|
|
|
|
|
|
|
def incr(self, key, expiry, elastic_expiry=False):
|
2017-04-22 10:28:31 +02:00
|
|
|
if not self.redis_instance.exists(key):
|
2017-04-22 15:35:26 +02:00
|
|
|
self.redis_instance.set(key, 1, ex=expiry)
|
2017-04-22 10:28:31 +02:00
|
|
|
else:
|
2017-04-22 15:35:26 +02:00
|
|
|
oldexp = oldexp = self.get_expiry(key) - time.time()
|
|
|
|
if oldexp <= 0:
|
|
|
|
self.redis_instance.delete(key)
|
|
|
|
return self.incr(key, expiry, elastic_expiry)
|
|
|
|
self.redis_instance.set(key, int(self.redis_instance.get(key))+1, ex=int(round(oldexp)))
|
|
|
|
return int(self.get(key))
|
2017-04-22 03:06:19 +02:00
|
|
|
|
|
|
|
def get(self, key):
|
2017-04-24 02:59:13 +02:00
|
|
|
value = self.redis_instance.get(key)
|
|
|
|
if value:
|
|
|
|
return int(value)
|
|
|
|
return 0
|
2017-04-22 10:28:31 +02:00
|
|
|
|
|
|
|
def reset(self):
|
|
|
|
return self.redis_instance.flushdb()
|