Django middleware and HttpRequest change
-
10-06-2021 - |
Question
I have a middleware to make some calculations/check for each incoming request. Some of view need this calculations result.
As I do not want to call the same code twice, I would like to put results to HttpRequest in middleware, so view will be able to read it.
Could you help me with right hint, how can I add an object to HttpRequest?
thanks
Solution
HttpRequest
is a normal class, you could directly assign the object to its instance, the request
, in the middleware. For example:
class MyMiddleware(object):
def process_request(self, request):
request.foo = 'bar'
OTHER TIPS
You can extend HttpResponse by using so-called "monkey-patch" method. For example you can easily add or replace methods and properties into HttpResponse
by calling following function from within your root __init__.py
or wsgi.py
or even settings.py
:
def apply_http_request_patch():
def get_property_value(request):
# return lazily evaluated value
from django.http import HttpRequest
HttpRequest.some_property = property(get_property_value)