Skip to content

Instantly share code, notes, and snippets.

@adamJLev
Last active November 14, 2022 15:54
Show Gist options
  • Save adamJLev/7e9499ba7e436535fd94 to your computer and use it in GitHub Desktop.
Save adamJLev/7e9499ba7e436535fd94 to your computer and use it in GitHub Desktop.
(DEPRECATED) Atomic transactions and Django Rest Framework
# NOTE This is probably no longer needed, now DRF does this
# automatically if you have ATOMIC_REQUESTS enabled.
# https://github.com/encode/django-rest-framework/pull/2887
from django.db import transaction
class AtomicMixin(object):
"""
Ensures we rollback db transactions on exceptions.
Idea from https://github.com/tomchristie/django-rest-framework/pull/1204
"""
@transaction.atomic()
def dispatch(self, *args, **kwargs):
return super(AtomicMixin, self).dispatch(*args, **kwargs)
def handle_exception(self, *args, **kwargs):
response = super(AtomicMixin, self).handle_exception(*args, **kwargs)
if getattr(response, 'exception'):
# We've suppressed the exception but still need to rollback any transaction.
transaction.set_rollback(True)
return response
@prudnikov
Copy link

This is not good. To achieve what this Mixin does you can just add ATIMIC_REQUESTS to the database settings. However, this is not recommended because you will start transaction for each read-only request as well. You want to define handlers for requests that change data: create, update, destroy. I published my version here https://gist.github.com/prudnikov/3a968a1ee1cf9b02730cc40bc1d3d9f2

@adamJLev
Copy link
Author

adamJLev commented May 4, 2020

@prudnikov well this was published 6 years ago, things have changed a lot since then both in django and in DRF.

Looks like DRF fixed this eventually: encode/django-rest-framework#2887

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment