From 1b626ea8361c13adb4b29bbc6cc9b252a6d927ec Mon Sep 17 00:00:00 2001 From: John Parton Date: Sat, 5 Aug 2023 00:08:45 -0500 Subject: [PATCH] Sync and async middleware. --- simple_history/middleware.py | 43 +++++++++++++++++++++++++----------- 1 file changed, 30 insertions(+), 13 deletions(-) diff --git a/simple_history/middleware.py b/simple_history/middleware.py index 9e469c173..ff0055e88 100644 --- a/simple_history/middleware.py +++ b/simple_history/middleware.py @@ -1,7 +1,23 @@ +from contextlib import contextmanager + +from asgiref.sync import iscoroutinefunction +from django.utils.decorators import sync_and_async_middleware + from .models import HistoricalRecords -class HistoryRequestMiddleware: +@contextmanager +def _context_manager(request): + HistoricalRecords.context.request = request + + try: + yield None + finally: + del HistoricalRecords.context.request + + +@sync_and_async_middleware +def HistoryRequestMiddleware(get_response): """Expose request to HistoricalRecords. This middleware sets request as a local context/thread variable, making it @@ -9,15 +25,16 @@ class HistoryRequestMiddleware: making a change. """ - def __init__(self, get_response): - self.get_response = get_response - - def __call__(self, request): - HistoricalRecords.context.request = request - try: - response = self.get_response(request) - except Exception as e: - raise e - finally: - del HistoricalRecords.context.request - return response + if iscoroutinefunction(get_response): + + async def middleware(request): + with _context_manager(request): + return await get_response(request) + + else: + + def middleware(request): + with _context_manager(request): + return get_response(request) + + return middleware \ No newline at end of file