Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django middleware and HttpRequest change

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

like image 899
Alan Harper Avatar asked May 23 '12 16:05

Alan Harper


People also ask

What is the role of middleware in Django?

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.

What is HttpRequest in Django?

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.

How do you determine at startup time if a piece of middleware should be used?

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.

Which of the following middleware are executed during the response phase?

In Django, middleware is a lightweight plugin that processes during request and response execution. Middleware is used to perform a function in the application.


1 Answers

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'
like image 177
okm Avatar answered Oct 26 '22 09:10

okm