-
-
Save ranvijay-sachan/061d2cdf3b9f9f6b2298a98da55b5071 to your computer and use it in GitHub Desktop.
Atomic transactions and Django Rest Framework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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