Skip to content

Instantly share code, notes, and snippets.

@yeazin
Created December 1, 2021 04:47
Show Gist options
  • Save yeazin/6f52c7e3af050742038cf3f3b1d8a8b5 to your computer and use it in GitHub Desktop.
Save yeazin/6f52c7e3af050742038cf3f3b1d8a8b5 to your computer and use it in GitHub Desktop.
Get the Current Request in Django/Django Rest Framework
'''
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)
# 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