Skip to content

Instantly share code, notes, and snippets.

@chris-martin
Created April 16, 2014 18:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chris-martin/10919294 to your computer and use it in GitHub Desktop.
Save chris-martin/10919294 to your computer and use it in GitHub Desktop.
from django.core.cache import cache
from contextlib import contextmanager
from datetime import timedelta
class LockUnavailable(Exception):
pass
class Lock(object):
def __init__(self, lock_id):
self.id = 'lock:%s' % lock_id
def acquire(self):
return cache.add(self.id, 'true', timedelta(minutes=2).seconds)
def release(self):
cache.delete(self.id)
@contextmanager
def lock(*ids):
acquired_locks = []
try:
for i in ids:
a = Lock(i)
if a.acquire():
acquired_locks.append(a)
else:
raise LockUnavailable(id)
yield True
finally:
[r.release() for r in acquired_locks]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment