From 13ec64e8c8a83c3f400638d341f0d0ba2b0b5419 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jes=C3=BAs=20Espino?= Date: Fri, 25 Oct 2013 07:39:31 +0200 Subject: [PATCH] Adding transaction rollback to exception_handler --- rest_framework/views.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/rest_framework/views.py b/rest_framework/views.py index e863af6dd..24b85c7b6 100644 --- a/rest_framework/views.py +++ b/rest_framework/views.py @@ -7,6 +7,8 @@ from django.core.exceptions import PermissionDenied from django.http import Http404 from django.utils.datastructures import SortedDict from django.views.decorators.csrf import csrf_exempt +from django.db import transaction + from rest_framework import status, exceptions from rest_framework.compat import smart_text, HttpResponseBase, View from rest_framework.request import Request @@ -366,6 +368,14 @@ class APIView(View): if response is None: raise + # We've suppressed the exception but still need to rollback any transaction. + if hasattr(transaction, 'set_rollback'): + # If running in >=1.6 then mark a rollback as required and let Django deal with it. + transaction.set_rollback(True) # Django 1.6+ + elif transaction.is_managed(): + # If running <=1.5 and TransactionMiddleware is installed then force it's rollback behavior. + TransactionMiddleware().process_exception(request, None) + response.exception = True return response