← Back to Django Course | Chapter 12: Signals & Middleware | Lesson 6 of 8

Custom Middleware लिखना

Custom middleware लिखने का मतलब है अपना खुद का checkpoint बनाना जिससे हर request को गुज़रना पड़े।
Syntax
markup
class MiddlewareName:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        request.extra = value  # before the view
        response = self.get_response(request)
        return response

Minimal Middleware Shape

हर middleware class को एक __init__ चाहिए जो get_response store करे, और एक __call__ जो इसे invoke करे और response return करे।

उदाहरण: The Minimal Middleware Shape

Every middleware class needs an __init__ that stores get_response, and a __call__ that invokes it and returns the response.

markup
class MinimalMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        return response
{# Django-only code -- models.py/views.py/urls.py/settings.py snippets, or template markup using Django template tags/variables -- can't run standalone via Judge0 or the browser preview, since it needs a real Django project. Only this course's pure-Python examples (example_lang == 'python', no Django imports) are actually runnable, so those still get the button below. #}

View से पहले Logic जोड़ना

self.get_response(request) से पहले रखा code आते समय चलता है, और views के बाद में उपयोग के लिए request object पर extra data attach कर सकता है।

उदाहरण: Adding Logic Before the View

Code placed before self.get_response(request) runs on the way in, and can attach extra data onto the request object for views to use later.

markup
class RequestTaggingMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        request.is_mobile = "Mobile" in request.META.get("HTTP_USER_AGENT", "")
        return self.get_response(request)
{# Django-only code -- models.py/views.py/urls.py/settings.py snippets, or template markup using Django template tags/variables -- can't run standalone via Judge0 or the browser preview, since it needs a real Django project. Only this course's pure-Python examples (example_lang == 'python', no Django imports) are actually runnable, so those still get the button below. #}

View के बाद Logic जोड़ना

self.get_response(request) के बाद रखा code जाते समय चलता है, और response को browser तक पहुंचने से पहले inspect या modify कर सकता है।

उदाहरण: Adding Logic After the View

Code placed after self.get_response(request) runs on the way out, and can inspect or modify the response before it reaches the browser.

markup
class CustomHeaderMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        response["X-Powered-By"] = "Django"
        return response
{# Django-only code -- models.py/views.py/urls.py/settings.py snippets, or template markup using Django template tags/variables -- can't run standalone via Judge0 or the browser preview, since it needs a real Django project. Only this course's pure-Python examples (example_lang == 'python', no Django imports) are actually runnable, so those still get the button below. #}

अपना Middleware Register करना

एक custom middleware class कुछ नहीं करता जब तक इसका dotted path settings.py में MIDDLEWARE list में जोड़ा न जाए।

उदाहरण: Registering Your Middleware

A custom middleware class does nothing until its dotted path is added to the MIDDLEWARE list in settings.py.

markup
MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "myapp.middleware.CustomHeaderMiddleware",
]
{# Django-only code -- models.py/views.py/urls.py/settings.py snippets, or template markup using Django template tags/variables -- can't run standalone via Judge0 or the browser preview, since it needs a real Django project. Only this course's pure-Python examples (example_lang == 'python', no Django imports) are actually runnable, so those still get the button below. #}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. __call__ से response return करना भूल जाना, जो project में हर request को break करता है।
  2. self.get_response(request) call न करना, जो view को कभी चलने से रोकता है।
  3. Middleware logic को __init__ में रखना बजाय __call__ के, इसलिए यह सिर्फ server startup पर एक बार चलता है, per request नहीं।
चैप्टर सारांश
  • Custom middleware __init__(self, get_response) और __call__(self, request) वाला एक class है।
  • Chain को काम करते रखने के लिए हमेशा self.get_response(request) call करें और इसका result return करें।
  • settings.py में MIDDLEWARE में इसका dotted path जोड़कर custom middleware register करें।
  • Per-request logic __call__ में रहता है, __init__ में नहीं।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.