Skip to content

Instantly share code, notes, and snippets.

@rafaelhenrique
Created December 14, 2015 17:54
Show Gist options
  • Save rafaelhenrique/f984b9505d2f7982f483 to your computer and use it in GitHub Desktop.
Save rafaelhenrique/f984b9505d2f7982f483 to your computer and use it in GitHub Desktop.
Implement an locker with Django Cache Framework (https://docs.djangoproject.com/en/1.9/topics/cache/)
# -*- coding: utf-8 -*-
# This code is inspired by:
# 1. http://docs.celeryproject.org/en/latest/tutorials/task-cookbook.html
# 2. http://loose-bits.com/2010/10/distributed-task-locking-in-celery.html
from django.core.cache import caches
class Locker(object):
"""
This class handling a basic lock using Django cache
"""
def __init__(self, lock_id, lock_expire):
"""
Initialize object Locker
Args:
lock_id (string): Any unique identificator;
lock_expire (float): Expire key in X seconds.
"""
self.lock_id = lock_id
self.lock_expire = lock_expire
self.cache = caches['database']
self.id = id(self)
def __enter__(self, *args, **kwargs):
"""
Create 2 keys in cache:
- first key: {<lockid> : True}
represents an lock
- second key: {<id of object> : "owner"}
represents owner of lock, only owner object has power
to release locker
"""
status = self.cache.add(self.lock_id, True, self.lock_expire)
if status:
self.cache.add(self.id, "owner", self.lock_expire)
return status
def __exit__(self, *args, **kwargs):
"""
Delete keys
"""
# if this is owner of lock then release lock
if self.cache.get(self.id):
self.cache.delete(self.lock_id)
self.cache.delete(self.id)
return True
# .... lines ommited here
# To configure your cache read https://docs.djangoproject.com/en/1.9/topics/cache/
# Cache
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'cache_default',
},
'database': {
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'cache',
}
}
# .... lines ommited here
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment