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
HttpRequest is a normal class, you can directly assign an object to its request instance in middleware. For instance:
HttpRequest
request
class MyMiddleware(object): def process_request(self, request): request.foo = 'bar'
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 :
HttpResponse
__init__.py
wsgi.py
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)
Source: https://habr.com/ru/post/916475/More articles:What is the best index for this delayed_job request for postgres? - sqlAfter a validation error, subsequent ajax requests receive values ββfrom the user interface components, not from Beans - javaPython functools.namedtuple - pythonHow to create a simple but well-structured musical note class (musical score) in java? - javaCreating javascript class unconfiguration via Reflection API - javaredirect_to with parameters. How to convey them in my opinion? - ruby-on-railsC Unions and polymorphism - cExpand alphabetical range to character list in Python - pythonHow to add a property to a document type in Umbraco from code? - c #Get a list of tests in the nunit library programmatically without having to run tests - c #All Articles