Django middleware change and HttpRequest change

I have middleware to do some calculations / checks for every incoming request. Some views need this calculation result.

Since I do not want to call the same code twice, I would like to put the results in HttpRequest in the middleware so that the viewer can read it.

Could you help me with the right hint how to add an object to HttpRequest?

thanks

+6
source share
2 answers

HttpRequest is a normal class, you can directly assign an object to its request instance in middleware. For instance:

 class MyMiddleware(object): def process_request(self, request): request.foo = 'bar' 
+6
source

You can extend HttpResponse using the so-called monkey-patch method. For example, you can easily add or replace methods and properties in HttpResponse by calling the following function from your __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) 
0
source

Source: https://habr.com/ru/post/916475/


All Articles