Skip to content

Instantly share code, notes, and snippets.

@krtk30
Forked from adamJLev/mixins.py
Created December 11, 2019 12:37
Show Gist options
  • Save krtk30/4ba5c505bdab196fe3c5fa2fea4b7f0d to your computer and use it in GitHub Desktop.
Save krtk30/4ba5c505bdab196fe3c5fa2fea4b7f0d to your computer and use it in GitHub Desktop.
Atomic transactions and Django Rest Framework
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
@varunajmera0
Copy link

It is not working with APIview

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