Skip to content

Commit

Permalink
Add redis storage backend
Browse files Browse the repository at this point in the history
  • Loading branch information
joealcorn committed Aug 19, 2015
1 parent 561d332 commit f1c73bc
Show file tree
Hide file tree
Showing 9 changed files with 75 additions and 0 deletions.
Empty file added celery_dedupe/__init__.py
Empty file.
3 changes: 3 additions & 0 deletions celery_dedupe/storage/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from .base import Storage

__all__ = ['Storage']
18 changes: 18 additions & 0 deletions celery_dedupe/storage/base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
class Storage(object):
'''
Defines the public api for Storages
'''

default_config = {}

def __init__(self, connection, **config):
self.connection = connection
self.config = self.default_config.copy()
self.config.update(config)

def obtain_lock(self, key, value):
'''
Responsible for obtaining a lock for the task
:returns boolean: Whether lock could be obtained or not
'''
raise NotImplementedError
21 changes: 21 additions & 0 deletions celery_dedupe/storage/redis.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from . import Storage

class RedisStorage(Storage):
'''
Storage class for redis.
Config:
expiry: number of seconds before expiring task, 0 to disable (default: 0)
'''

default_config = {
'expiry': 0,
}

def obtain_lock(self, key, value):
obtained = self.connection.setnx(key, value)
if self.config['expiry'] and obtained:
self.connection.expire(key, self.config['expiry'])

return obtained

3 changes: 3 additions & 0 deletions dev-requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
exam==0.10.5
pytest==2.7.2
redis==2.10.3
Empty file added tests/__init__.py
Empty file.
Binary file added tests/__init__.pyc
Binary file not shown.
Binary file not shown.
30 changes: 30 additions & 0 deletions tests/test_storages.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
from uuid import uuid4
from redis import StrictRedis

from celery_dedupe.storage.redis import RedisStorage

class TestRedisStorage(object):

@property
def redis(self):
if hasattr(self, '_redis'):
return self._redis

self._redis = StrictRedis()
return self._redis

def test_lock_obtained(self):
storage = RedisStorage(self.redis)
assert storage.obtain_lock(uuid4(), '1')

def test_lock_obtained_with_expiry(self):
key = uuid4()
storage = RedisStorage(self.redis, expiry=10)
assert storage.obtain_lock(key, '1')
assert self.redis.ttl(key) == 10

def test_already_locked(self):
key = uuid4()
self.redis.setex(key, '1', 10)
storage = RedisStorage(self.redis, expiry=10)
assert not storage.obtain_lock(key, '1')

0 comments on commit f1c73bc

Please sign in to comment.