Skip to content

Commit

Permalink
Sync and async middleware.
Browse files Browse the repository at this point in the history
  • Loading branch information
john-parton committed Aug 5, 2023
1 parent 2e3e325 commit 1b626ea
Showing 1 changed file with 30 additions and 13 deletions.
43 changes: 30 additions & 13 deletions simple_history/middleware.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,40 @@
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
available to the model-level utilities to allow tracking of the authenticated user
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):

Check warning on line 30 in simple_history/middleware.py

View check run for this annotation

Codecov / codecov/patch

simple_history/middleware.py#L30

Added line #L30 was not covered by tests
with _context_manager(request):
return await get_response(request)

Check warning on line 32 in simple_history/middleware.py

View check run for this annotation

Codecov / codecov/patch

simple_history/middleware.py#L32

Added line #L32 was not covered by tests

else:

def middleware(request):
with _context_manager(request):
return get_response(request)

return middleware

0 comments on commit 1b626ea

Please sign in to comment.