Skip to content

Commit

Permalink
Global request middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
f213 committed Sep 4, 2024
1 parent 9f55943 commit 620ae0d
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/core/conf/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"core.middleware.set_user_from_non_django_authentication.JWTAuthMiddleware",
"core.middleware.set_user_from_non_django_authentication.TokenAuthMiddleware",
"core.middleware.global_current_user.set_global_user",
"core.middleware.global_request.set_global_request",
"axes.middleware.AxesMiddleware",
]

Expand Down
18 changes: 18 additions & 0 deletions src/core/middleware/global_request.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from typing import Callable

from django.http import HttpRequest, HttpResponse

from core.request import set_request, unset_request


def set_global_request(get_response: Callable[[HttpRequest], HttpResponse]) -> Callable[[HttpRequest], HttpResponse]:
def middleware(request: HttpRequest) -> HttpResponse:
set_request(request) # type: ignore

response = get_response(request)

unset_request()

return response

return middleware
25 changes: 25 additions & 0 deletions src/core/request.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from threading import current_thread, local

from rest_framework.request import Request

_thread_locals = local()


def get_request() -> Request | None:
return getattr(_thread_locals, _thread_key(), None)


def set_request(request: Request) -> None:
setattr(_thread_locals, _thread_key(), request)


def unset_request() -> None:
thread_key = _thread_key()

if hasattr(_thread_locals, thread_key):
delattr(_thread_locals, thread_key)


def _thread_key() -> str:
thread_name = current_thread().name
return f"request_{thread_name}"

0 comments on commit 620ae0d

Please sign in to comment.