views:

744

answers:

4

I want to raise error when a user tries to delete an object when some other users are active in update_object view. I feel some sort of mutex-like locking mechanism is needed for that. Do you have any suggestions?

A: 

I'd suggest a simple read-write lock, as you don't want to block users from accessing the object concurrently (only from editing).

A general approach to doing this would be to create a function that maintains a count of active readers. When you need to write to that object, you would create another function that would prevent new readers from getting access (think a maintenance page), and possibly redirect existing readers away. Once there are no more readers left, you would complete your write, then unlock the object.

Dana the Sane
+4  A: 

So, there are a handful of ways to do what you're asking. But a good number of them are not going to be implementation independent: you could use locks or rlocks, but they will really only work on 100% threaded servers and probably not at all in a fork/pre-fork implementation.

That more or less means the locking implementation will be up to you. Two ideas:

  1. .lock file on your file system
  2. locked property in your model class

In both cases, you have to manually set the lock object on update and check against it on delete. Try something like:

def safe_update(request,model,id):
    obj = model.objects.get(id)
    if obj.locked:
        raise SimultaneousUpdateError #Define this somewhere
    else:
        obj.lock()
        return update_object(request,model,id)

# In models file
class SomeModel(models.Model):
    locked = models.BooleanField(default = False)
    def lock(self):
        self.locked = True
        super(models.Model,self).save()
    def save(self):
        # overriding save because you want to use generic views
        # probably not the best idea to rework model code to accomodate view shortcuts
        # but I like to give examples.
        self.locked = False
        # THIS CREATES A DIFFERENT CRITICAL REGION!
        super(models.Model,self).save()

This is indeed a clumsy implementation that you'll have to clean up. You may not be comfortable with the fact that a different critical region has been created, but I don't see how you'll do much better if your using the database as an implementation without making the implementation much more complicated. (One option would be to make the locks entirely separate objects. Then you could update them after the save() method is called. But I don't feel like coding that up.) If you really want to use a file-based locking system, that would also solve the problem. If you're database-hit-paranoid, this might be the thing for you. Something like:

class FileLock(object):
    def __get__(self,obj):
        return os.access(obj.__class__+"_"+obj.id+".lock",os.F_OK)
    def __set__(self,obj,value):
        if not isinstance(value,bool):
            raise AttributeError
        if value:
            f = open(obj.__class__+"_"+obj.id+".lock")
            f.close()
        else:
            os.remove(obj.__class__+"_"+obj.id+".lock")
    def __delete__(self,obj):
        raise AttributeError

 class SomeModel(models.Model):
     locked = FileLock()
     def save(self):
         super(models.Model,self).save()
         self.locked = False

Anyway, maybe there's some way to mix and match these suggestions to your taste?

David Berger
+1 for detailed examples and description
Jarret Hardie
I was planning to make something like that, but looking for a built-in way first. As there is no clue of built-in lock, I'll accept your answer. Thanks!
kokeksibir
+1  A: 

Since your scope is limited to deletes, and not also updates, one option would be to rethink the idea of a "delete" as an "unpublish" action. For instance, take the following model:

class MyManager(models.Manager):
    def get_query_set(self):
        super(MyManager, self).get_query_set().filter(published=True)

class MyModel(models.Model):
    objects = MyManager()
    published = models.BooleanField(default=True)
    ... your fields ...

    def my_delete(self):
        self.published = False
        super(MyModel, self).save()

    def save(self):
        self.published = True
        super(MyModel, self).save()

In this way, whenever an edit is committed, it is visible to all users... but others are still free to delete items. One advantage of this technique is you don't have to have any extra logic to lock items and present a different UI to the user. Disadvantages are extra space used in the db table, and the rare circumstances where a deleted item "magically" reappears.

(This is probably just a starting point. If you took this path, you'd likely want to do a variation on this idea depending on your use case.)

Daniel
I like the "unpublish" idea, yet it is a work around rather than a solution. I'll keep it in mind and try it if other I couldn't manage with someway else. Thanks!
kokeksibir
A: 

For future reference, check out http://github.com/stdbrouw/django-locking

Stijn Debrouwere