Django decorator @ transaction.non_atomic_requests not working in ViewSet method

Recently I was faced with the need to turn off transaction requests in one of my ideas to be able to call db.connection.close()and connect()during inquiries in order to improve performance.

I have a ViewSet DRF and use the following very simple view to make sure the non_atomic_requests decoder does not seem to have any effect. ATOMIC_REQUESTS=Trueincluded in settings.pyand DEBUG=False.

from django.db import transaction    

@transaction.non_atomic_requests
def create(self, *args, **kwargs):
    m = MyModel(stuff="hello")
    m.save()
    raise Exception('exception! row should still be saved though')
    return Response()

After calling the view, I open the Django shell and verify that the number of lines in db has not increased, even if it should be. Also, by opening the debugger during the request to stop execution after the line m.save(), I can observe in the Django shell that the new line is not yet visible.

If I install ATOMIC_REQUESTS=Falsein settings.py, the code works as expected, and the number of lines in db increases by one, even if an error occurs before returning from the view.

When ATOMIC_REQUESTS=False, using the @transaction.atomicdecorator works as expected. Since there is a workaround, I could use it to set any other representation as atomic and not ...

, . - , , ?

Python 3.6, Django 2.0 DRF 3.7.7.

+4
1

, non_atomic_requests , .

create - viewet, . Django dispatch, method_decorator.

@method_decorator(transaction.non_atomic_requests, name='dispatch') 
class MyViewSet(ViewSet):
    ...

    def create(self, *args, **kwargs):
        ...

, , . , , viewet, create.

non_atomic_requests , Django , , . transaction.atomic - Django , .

+2

Source: https://habr.com/ru/post/1696283/


All Articles