Middleware in Django provides a powerful mechanism to process requests and responses globally. It allows developers to hook into Django’s request/response lifecycle to apply logic before the view executes and after the response is generated.
In Django, middleware is a framework of hooks into the request/response processing. It is a lightweight, low-level plugin system for globally altering Django’s input or output.
Middleware components are executed in the order they are listed in the MIDDLEWARE setting. Each middleware can implement lifecycle methods that hook into request handling.
# Custom middleware to log request processing time
import time
class SimpleLoggingMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
start_time = time.time()
response = self.get_response(request)
duration = time.time() - start_time
print(f"Request took {duration:.2f} seconds")
return response
This middleware calculates the time taken for each request and prints it to the server console, helping developers analyze performance.
Click "Send Request" to see how data flows through the "Onion Architecture" of Middleware.
Request ➜ Middleware ➜ View ➜ Middleware ➜ Response