Skip to content

Instantly share code, notes, and snippets.

@ranvijay-sachan
Forked from adamJLev/mixins.py
Created February 13, 2019 09:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ranvijay-sachan/061d2cdf3b9f9f6b2298a98da55b5071 to your computer and use it in GitHub Desktop.
Save ranvijay-sachan/061d2cdf3b9f9f6b2298a98da55b5071 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment