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
Middleware is a framework of hooks into Django's request/response processing. It's a light, low-level “plugin” system for globally altering Django's input or output. Each middleware component is responsible for doing some specific function.
Django uses request and response objects to pass state through the system. When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Then Django loads the appropriate view, passing the HttpRequest as the first argument to the view function.
Marking middleware as unused It's sometimes useful to determine at startup time whether a piece of middleware should be used. In these cases, your middleware's __init__() method may raise MiddlewareNotUsed . Django will then remove that middleware from the middleware process and log a debug message to the django.
In Django, middleware is a lightweight plugin that processes during request and response execution. Middleware is used to perform a function in the application.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With