Implementing a middleware application is not difficult. A middleware application is a basic Python class that defines one or more functions that conform to a specific API. The class does not need to inherit from any other class. However, it does need to define one or more of the following middleware API functions:
process_request(self, request) runs before processing the request.
process_view(self, request, view, args, kwargs) runs before calling the view function.
process_response(self, request, response) runs after the response has been generated.
process_exception(self, request, exception) runs when an exception has been raised and not handled.
To implement a middleware application, simply create a Python class and add a definition to one or more of these functions. Then place the module somewhere in the Python path and add an entry for it in the MIDDLEWARE_CLASSES setting.
You can also define an __init__(self) function in the middleware class. The __init__() function should take no arguments except self. You can use the __init__() function to perform some operations whenever the middleware object is instantiated.
Watch Out!
For long-running server processes, the middleware class is instantiated only once. Therefore, you cannot be certain that the __init__() function will be run every time a request runs.