from datetime import datetime, timedelta from django.db import models class LockManager(models.Manager): """ Usage: # Lock 'sync' for 2 minutes. if Lock.objects.lock('sync', 120): # This code will be accessed only # once per 2 minutes. """ def get_lock(self, name): try: return self.get(name=name) except Lock.DoesNotExist: return Lock(name=name) def lock(self, name, seconds): """ Set new lock and return True, but if already locked, do nothing and return False. ``name`` Lock name, any string. ``seconds`` For how many seconds ``name`` must be locked. """ now = datetime.now() lock = self.get_lock(name) if lock.locked and lock.locked > now: return False else: lock.locked = now + timedelta(seconds=seconds) lock.save() return True class Lock(models.Model): name = models.CharField(max_length=16, unique=True) locked = models.DateTimeField() objects = LockManager()