Created
December 1, 2021 04:47
-
-
Save yeazin/6f52c7e3af050742038cf3f3b1d8a8b5 to your computer and use it in GitHub Desktop.
Get the Current Request in Django/Django Rest Framework
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 custom Middilware Functionality | |
''' | |
from threading import current_thread | |
from django.utils.deprecation import MiddlewareMixin | |
#underscore remove | |
_requests = {} | |
def current_request(): | |
return _requests.get(current_thread().ident, None) | |
class RequestWare(MiddlewareMixin): | |
def process_request(self, request): | |
_requests[current_thread().ident] = request | |
def process_response(self, request, response): | |
# when response is ready, request should be flushed | |
_requests.pop(current_thread().ident, None) | |
return response | |
def process_exception(self, request, exception): | |
# if an exception has happened, request should be flushed too | |
_requests.pop(current_thread().ident, None) |
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
# add the custom middleware in settngs.py | |
# middleware section | |
MIDDLEWARE = [ | |
'YourRootFile.current_request.RequestWare' | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment