Created
December 14, 2015 17:54
-
-
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/)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# .... 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