Skip to content

Instantly share code, notes, and snippets.

@theY4Kman
Created March 18, 2015 17:44
Show Gist options
  • Select an option

  • Save theY4Kman/6795117111ff77ab57b8 to your computer and use it in GitHub Desktop.

Select an option

Save theY4Kman/6795117111ff77ab57b8 to your computer and use it in GitHub Desktop.
Django cache-based lock, originally for distributed Celery tasks
import gevent
from django.core.cache import cache
class CacheLock(object):
"""A lock backed by redis"""
def __init__(self, lock_id, expiry=60 * 5):
"""
:param lock_id: unique key for lock (unique through Django cache)
:param expiry: expiry of lock, in seconds
"""
self.lock_id = lock_id
self.expiry = expiry
def __enter__(self):
self.acquire()
def __exit__(self, exc_type, exc_val, exc_tb):
self.release()
def acquire(self, block=True):
while not self._acquire():
if block:
gevent.sleep(0.1)
else:
return False
return True
def release(self):
cache.delete(self.lock_id)
def _acquire(self):
return cache.add(self.lock_id, 'true', self.expiry)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment