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
@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