Last active
November 14, 2022 15:54
-
-
Save adamJLev/7e9499ba7e436535fd94 to your computer and use it in GitHub Desktop.
(DEPRECATED) 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
# 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 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
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