-
Notifications
You must be signed in to change notification settings - Fork 66
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
Showing
3 changed files
with
44 additions
and
0 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
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 |
---|---|---|
@@ -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 |
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 |
---|---|---|
@@ -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}" |