This repository created in attach to this post
In short, middlewares are classes that contain some functions called before and after all view functions. For more detail on middleware, you can click here.
the only requirement for a class to be a middleware is that middleware must have at least one of the following methods:
- process_request
- process_view
- process_response
- process_exception
Every Django project has a list called MIDDLEWARES
(or MIDDLEWARE_CLASSES
in older versions) in settings.py
that contains the path of every middleware that has at least one of the methods mentioned above.
after request received by the framework, WSGI Handler builds a HttpRequest
object for passing to view functions and in this process it iterates through the list and it will call process_request
method from every class in the list that contains this method. (if one class in the list doesn't have process_request
, it will just get skipped.)
after building HttpRequest
object and before passing it to every view function WSGI Handler will call process_view
method of middlewares.
process_request
andprocess_view
methods should returnNone
that in this case WSGI Handler will continue the cycle; or this methods should alternatively returnHttpResponse
that in this case WSGI Handler will beginprocess_response
cycle. if a view function raise an exception WSGI Handler will beginprocess_exception
cycle and if a view function returnsHttpResponse
object, WSGI Handler will beginprocess_response
cycle.- unlike
process_request
andprocess_view
methods,process_response
andprocess_exception
can only modify the data of response/exception