Skip to content

Commit

Permalink
Add check method to all storage classes
Browse files Browse the repository at this point in the history
  • Loading branch information
alisaifee committed Jun 7, 2015
1 parent b6b755d commit a3df0f7
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
32 changes: 31 additions & 1 deletion limits/storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,12 @@ def get_expiry(self, key):
"""
raise NotImplementedError


@abstractmethod
def check(self):
"""
check if storage is healthy
"""
raise NotImplementedError


class LockableEntry(threading._RLock):
Expand Down Expand Up @@ -204,6 +209,13 @@ def get_moving_window(self, key, limit, expiry):
return int(item.atime), acquired
return int(timestamp), acquired

def check(self):
"""
check if storage is healthy
"""
return True


class RedisStorage(Storage):
"""
rate limit storage with redis as backend
Expand Down Expand Up @@ -308,6 +320,15 @@ def get_expiry(self, key):
"""
return int((self.storage.ttl(key) or 0) + time.time())

def check(self):
"""
check if storage is healthy
"""
try:
return self.storage.ping()
except: # noqa
return False

class MemcachedStorage(Storage):
"""
rate limit storage with memcached as backend
Expand Down Expand Up @@ -398,3 +419,12 @@ def get_expiry(self, key):
"""
return int(float(self.storage.get(key + "/expires") or time.time()))

def check(self):
"""
check if storage is healthy
"""
try:
self.call_memcached_func(self.storage.stats)
return True
except: # noqa
return False
5 changes: 5 additions & 0 deletions tests/test_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ def test_storage_string(self):
self.assertTrue(isinstance(storage_from_string("memcached://localhost:11211"), MemcachedStorage))
self.assertRaises(ConfigurationError, storage_from_string, "blah://")

def test_storage_check(self):
self.assertTrue(storage_from_string("memory://").check())
self.assertTrue(storage_from_string("redis://localhost:6379").check())
self.assertTrue(storage_from_string("memcached://localhost:11211").check())

def test_in_memory(self):
with hiro.Timeline().freeze() as timeline:
storage = MemoryStorage()
Expand Down

0 comments on commit a3df0f7

Please sign in to comment.