Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

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 theY4Kman/ed220565adb36a122e191b62f37bd2e5 to your computer and use it in GitHub Desktop.
Save theY4Kman/ed220565adb36a122e191b62f37bd2e5 to your computer and use it in GitHub Desktop.
A Django middleware which rolls back any DB changes at the end of the request. I found it useful when profiling SQL queries from POST/PUT requests, because I didn't have to find or generate so much test data
import logging
from contextlib import contextmanager
from django.db import transaction
from django.http import HttpRequest
from django.utils.deprecation import MiddlewareMixin
logger = logging.getLogger(__name__)
@contextmanager
def rollback():
with transaction.atomic():
yield
transaction.rollback()
def rollback_transaction_middleware(get_response):
"""Rolls back transaction at end of request if ?rollback passed
"""
def _rollback_transaction_middleware(request: HttpRequest):
if 'rollback' in request.GET:
with rollback():
return get_response(request)
else:
return get_response(request)
return _rollback_transaction_middleware
class RollbackTransactionMiddleware:
def process_view(self, request, view):
if 'rollback' in request.GET:
transaction.set_autocommit(False)
self.sid = transaction.savepoint()
def process_response(self, request, response):
if 'rollback' in request.GET:
transaction.savepoint_rollback(self.sid)
transaction.set_autocommit(True)
logger.debug('Rolling back %s', self.sid)
print('Rolling back', self.sid)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment