MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Custom Middleware0%
Study Materials
Django for Backend DevelopmentProgress 0%
1.1Installing Django & Environment Setup1.2Django Project Structure1.3Creating First Django App
7.1Custom Middleware7.2CSRF Protection7.3Security Best Practices
HomeTutorialsDjango for Backend DevelopmentCustom Middleware
CSRF Protection

Custom Middleware

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

Django processes incoming HTTP requests and outgoing HTTP responses through an extensible pipeline known as Middleware. Each middleware component behaves like an onion layer: it can inspect, alter, or short-circuit incoming requests before they reach the view, and post-process outgoing responses before they are returned to the client browser.


1. The Middleware Execution Pipeline

1Incoming Request:
2Client ──► [SecurityMiddleware] ──► [SessionMiddleware] ──► [AuthMiddleware] ──► View Function
3 │
4Outgoing Response: ▼
5Client ◄── [SecurityMiddleware] ◄── [SessionMiddleware] ◄── [AuthMiddleware] ◄── Response
  • Top-to-Bottom on Requests: Middlewares execute in the exact order listed in settings.MIDDLEWARE.
  • Bottom-to-Top on Responses: Middlewares execute in reverse order when returning responses.

2. Anatomy of Modern Callable Middleware

Modern Django middleware is structured as a Python callable (function or class) taking get_response:

1# config/middleware/request_timer.py
2import time
3import logging
4 
5logger = logging.getLogger("django.performance")
6 
7class PerformanceTimingMiddleware:
8 def __init__(self, get_response):
9 self.get_response = get_response
10 # One-time configuration and initialization upon server boot
11 
12 def __call__(self, request):
13 # 1. Code executed BEFORE the view is called:
14 start_time = time.monotonic()
15 
16 # 2. Hand over request to next layer (or view)
17 response = self.get_response(request)
18 
19 # 3. Code executed AFTER the view completes:
20 duration = time.monotonic() - start_time
21 duration_ms = round(duration * 1000, 2)
22 
23 # Attach custom performance header to outgoing HTTP response
24 response["X-Response-Time-Ms"] = str(duration_ms)
25 
26 if duration_ms > 500:
27 logger.warning(
28 f"Slow Request Detected: {request.method} {request.path} took {duration_ms}ms"
29 )
30 
31 return response

3. Special Middleware Hooks

Classes can implement specialized hook methods for specific interception points:

  • process_view(request, view_func, view_args, view_kwargs): Called just before Django calls the view function. Returning an HttpResponse bypasses the view entirely.
  • process_exception(request, exception): Called when a view raises an unhandled exception. Ideal for reporting crashes to Sentry or Datadog.
  • process_template_response(request, response): Called if the view returned a TemplateResponse object, allowing manipulation of template context before rendering.

4. IP Whitelisting & API Rate Limiting Middleware

1# config/middleware/ip_guard.py
2from django.http import HttpResponseForbidden
3from django.conf import settings
4 
5class IPWhitelistMiddleware:
6 def __init__(self, get_response):
7 self.get_response = get_response
8 
9 def __call__(self, request):
10 # Restrict /admin/ access to corporate VPN IP ranges
11 if request.path.startswith("/admin/"):
12 client_ip = self.get_client_ip(request)
13 if client_ip not in settings.ADMIN_IP_WHITELIST:
14 return HttpResponseForbidden("Access Denied: IP address not in corporate whitelist.")
15 
16 return self.get_response(request)
17 
18 def get_client_ip(self, request):
19 x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
20 if x_forwarded_for:
21 return x_forwarded_for.split(",")[0].strip()
22 return request.META.get("REMOTE_ADDR")

5. Registering Custom Middleware in settings.py

1MIDDLEWARE = [
2 "django.middleware.security.SecurityMiddleware",
3 "django.contrib.sessions.middleware.SessionMiddleware",
4 "django.middleware.common.CommonMiddleware",
5 # Custom Enterprise Middlewares:
6 "config.middleware.request_timer.PerformanceTimingMiddleware",
7 "config.middleware.ip_guard.IPWhitelistMiddleware",
8 "django.middleware.csrf.CsrfViewMiddleware",
9 "django.contrib.auth.middleware.AuthenticationMiddleware",
10 "django.contrib.messages.middleware.MessageMiddleware",
11]

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
In what order do middleware components execute during the lifecycle of an HTTP request and response?
Question 2
What does returning an HttpResponse directly from a middleware before calling get_response(request) do?
Question 3
How do you extract the real client IP address when Django sits behind a reverse proxy (e.g. Nginx or Cloudflare)?
Question 4
When is the process_exception(request, exception) hook called?
Question 5
Why is __init__(self, get_response) only executed once in class-based middleware?
Next Lesson

CSRF Protection

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Routing APIs with DRFCSRF Protection

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Django for Backend Development with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext