Middleware lets you run code before and after Django handles a web request. It helps you change requests or responses easily.
0
0
Request/response middleware flow in Django
Introduction
You want to check or change user login status before views run.
You need to add headers or cookies to every response.
You want to log details about each request and response.
You want to block certain IP addresses from accessing your site.
You want to handle errors globally and show custom error pages.
Syntax
Django
class MyMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Code before view response = self.get_response(request) # Code after view return response
The __init__ method runs once when Django starts.
The __call__ method runs for each request, before and after the view.
Examples
This middleware prints messages before and after the view runs.
Django
class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): print('Before view') response = self.get_response(request) print('After view') return response
This middleware adds a custom header to every response.
Django
class AddHeaderMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) response['X-Custom-Header'] = 'Hello' return response
Sample Program
This middleware logs the URL path of each request and the status code of the response.
Django
class LogMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): print(f'Request path: {request.path}') response = self.get_response(request) print(f'Response status: {response.status_code}') return response
OutputSuccess
Important Notes
Middleware order matters: Django runs them in the order listed in MIDDLEWARE settings.
Middleware can modify both request and response objects.
Use middleware for cross-cutting concerns like logging, security, and headers.
Summary
Middleware runs code before and after views to handle requests and responses.
Define middleware as a class with __init__ and __call__ methods.
Middleware helps add features like logging, headers, and security checks easily.