middleware.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import threading
  2. try:
  3. from django.utils.deprecation import MiddlewareMixin
  4. except ImportError:
  5. MiddlewareMixin = object
  6. class CrequestMiddleware(MiddlewareMixin):
  7. """
  8. Provides storage for the "current" request object, so that code anywhere
  9. in your project can access it, without it having to be passed to that code
  10. from the view.
  11. """
  12. _requests = {}
  13. def process_request(self, request):
  14. """
  15. Store the current request.
  16. """
  17. self.__class__.set_request(request)
  18. def process_response(self, request, response):
  19. """
  20. Delete the current request to avoid leaking memory.
  21. """
  22. self.__class__.del_request()
  23. return response
  24. @classmethod
  25. def get_request(cls, default=None):
  26. """
  27. Retrieve the request object for the current thread, or the optionally
  28. provided default if there is no current request.
  29. """
  30. return cls._requests.get(threading.current_thread(), default)
  31. @classmethod
  32. def set_request(cls, request):
  33. """
  34. Save the given request into storage for the current thread.
  35. """
  36. cls._requests[threading.current_thread()] = request
  37. @classmethod
  38. def del_request(cls):
  39. """
  40. Delete the request that was stored for the current thread.
  41. """
  42. cls._requests.pop(threading.current_thread(), None)