In Django, middleware provides a way to process requests and responses globally before they reach the view or after the view has processed the response. You can write custom middleware to add logging, authentication checks, or response modifications across the entire application.
MIDDLEWARE
# Custom middleware to log request path and timestamp
import datetime
class RequestLoggingMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print(f"Request at {timestamp}: {request.path}")
response = self.get_response(request)
return response
# Registering custom middleware in Django
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'myapp.middleware.RequestLoggingMiddleware',
]
# Blocking unauthenticated users using middleware
from django.http import HttpResponseForbidden
class CustomAuthenticationMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if not request.user.is_authenticated:
return HttpResponseForbidden("You must be logged in to access this page.")
return self.get_response(request)
Every incoming request prints a timestamp and URL in the server console. Unauthenticated users are blocked globally before views execute.
Configure the simulator below to visualize how the middleware chain handles a request.