Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django transaction management with class based view

Tags:

python

django

I have a class based view and that has method post as follows

class Comment(View):

    def dispatch(self, request, *args, **kwargs):
        super(Comment, self).dispatch(request, *args, **kwargs)

    @method_decorator(transaction.non_atomic_requests)
    def post(self, request, *args, **kwargs):
        <Some code>

In above example transaction.non_atomic_requests does not make post method non atomic, but if I use same decorator for dispatch method then it works? Why?

I am using django 1.9

like image 690
at S Avatar asked Sep 11 '25 15:09

at S


1 Answers

When you use the transaction.non_atomic_requests decorator, it sets an attribute _non_atomic_requests on the decorated object.

Django then checks for the _non_atomic_requests attribute when the view runs.

When Django runs a class based view, it doesn't run the dispatch method directly, it runs the view that is returned by the as_view() method.

There is code in the as_view() method that copies attributes like _non_atomic_requests from the dispatch method to the view that is returned.

However the as_view method does not copy attributes from any other methods like get or post. When you decorate the post method, the _non_atomic_requests attribute is not copied to the view, so the decorator does not work.

Therefore, you must apply decorators like transaction.non_atomic_requests or csrf_exempt to the dispatch method.

like image 197
Alasdair Avatar answered Sep 13 '25 04:09

Alasdair