-
-
Notifications
You must be signed in to change notification settings - Fork 480
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
2e3e325
commit 1b626ea
Showing
1 changed file
with
30 additions
and
13 deletions.
There are no files selected for viewing
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
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): | ||
with _context_manager(request): | ||
return await get_response(request) | ||
|
||
else: | ||
|
||
def middleware(request): | ||
with _context_manager(request): | ||
return get_response(request) | ||
|
||
return middleware |