Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django middleware difference between process_request and process_view

I am little bit confused on process_request and process_view.

Process request is something that u want to pass on view with request. Example can be taken from request.user.

Then what does process_view does ? Is it for executing any view initially befor calling any url ? Like initially I want to show home view but this can be done from url too.

Can anyone give me example when to use process_view ?

Thank you

like image 243
varad Avatar asked Oct 29 '15 06:10

varad


People also ask

What is Get_response in Django middleware?

get_response(request) # Code to be executed for each request/response after # the view is called. return response. The get_response callable provided by Django might be the actual view (if this is the last listed middleware) or it might be the next middleware in the chain.

What is middle ware 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.

Can we create custom middleware in Django?

Custom middleware in Django is created either as a function style that takes a get_response callable or a class-based style whose call method is used to process requests and responses. It is created inside a file middleware.py . A middleware is activated by adding it to the MIDDLEWARE list in Django settings.

Is middleware a decorator?

Middleware and decorators are similar and can do the same job. They provide a means of inserting intermediary effects either before or after other effects downstream in the chain/stack.


1 Answers

process_request is called before Django determines which view should handle the request (hence, it's only parameter is the request).

process_view is called after Django determines which view will handle the request, but before that view is called. It will have access to the request object, along with the view that will handle it and the parameters that will be passed to that view.

Whenever you need to know the view that will be used for a request, you can use process_view. A good example for this is Django's CSRF Middleware process_view, which will not enforce CSRF protection if a csrf_exempt decorator is present on the view the request is meant for:

def process_view(self, request, callback, callback_args, callback_kwargs):
    [...]

    if getattr(callback, 'csrf_exempt', False):
       return None

    [...]
like image 119
Adrian Ghiuta Avatar answered Oct 12 '22 02:10

Adrian Ghiuta