File: middleware.py

package info (click to toggle)
python-django-simple-history 3.7.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,124 kB
  • sloc: python: 8,454; makefile: 186
file content (43 lines) | stat: -rw-r--r-- 1,083 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
from contextlib import contextmanager

from asgiref.sync import iscoroutinefunction
from django.utils.decorators import sync_and_async_middleware

from .models import HistoricalRecords


@contextmanager
def _context_manager(request):
    HistoricalRecords.context.request = request

    try:
        yield None
    finally:
        try:
            del HistoricalRecords.context.request
        except AttributeError:
            pass


@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.
    """

    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