Django - access class attributes of a class-based view in middleware

650 Views Asked by At

I have a couple of views and each of them must be accesed by no more than one user at a time. Therefore I use a locking service for this. My idea is as follows:

- Declare each view like this

class DummyView(View):
    lock = Lock()
    def dispatch(self, request, *args, **kwargs):
        ...

- In a middleware, do something like this

class Middleware:
    ...
    def __call__(self, request):
        # lock = view.get_lock_if_it_has_one (this is what I need help with)
        lock.acquire()

        response = self.get_response(request)

        lock.release()
        return response

How can I access the lock attribute of the view as described?

1

There are 1 best solutions below

4
On

Unsure if you can access a view inside the middleware, so I am just suggesting something more simple and easy to implement / understand.

Simply create a model Lock which would have the fields view_name (char field), user (foreign key) & is_acquired (bool). Then, when you want to lock the view for a given request.user (check for anonymous users), simply instantiate the Lock model with the user & view_name, then do a .acquire() which basically changes is_acquired to True (and saves).

And when you want to check if a lock has been acquired, simply check if the given entry .exists().

If you want, you can run a periodic task that expires old locks.