Implementing Global Request Processing with Django Middleware

Middleware provides a way to process requests and responses globally in Django applications. Instead of decorating individual view functions, middleware allows centrailzed request handling with several hook points during the request/response cycle.

Middleware Basics

Middleware components are Python classes that implement specific methods Django calls during request processing. The default middleware stack in settings.py includes:

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',
]

Custom Middleware Implementation

Create a middleware class by subclassing MiddlewareMixin and implementing hook methods:

from django.utils.deprecation import MiddlewareMixin

class RequestLogger(MiddlewareMixin):
    def process_request(self, request):
        print(f"Processing request: {request.path}")
        
    def process_response(self, request, response):
        print(f"Returning response for: {request.path}")
        return response

Middleware Execution Flow

  1. process_request() - Runs before view execution in registration order
  2. process_view() - Runs after URL routing but before view execution
  3. View function executes
  4. process_response() - Runs after view execution in reverse registration order
  5. process_exception() - Runs only if view raises an exception
  6. process_template_response() - Runs for template responses

Authentication Middleware Example

class AuthMiddleware(MiddlewareMixin):
    allowed_paths = ['/login/', '/public/']
    
    def process_request(self, request):
        if request.path in self.allowed_paths:
            return
            
        if not request.session.get('authenticated'):
            return redirect(f'/login/?next={request.path}')

Register custom middleware in settings.py:

MIDDLEWARE = [
    # ... default middleware ...
    'app.middleware.AuthMiddleware',
]

Key considerations:

  • Middleware executes for every request - keep it lightweight
  • Order matters - dependencies between middleware must be considered
  • Repsonse processing happens in reverse order of request processing

Tags: Django middleware python web-development Authentication

Posted on Mon, 11 May 2026 00:35:30 +0000 by ntjang