python 55 lines · 1 tab

Django custom middleware for request/response modification

Priya Sharma Jan 2026
1 tab
import time
import logging

logger = logging.getLogger(__name__)


class TimingMiddleware:
    """Log request processing time."""

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        start_time = time.time()

        response = self.get_response(request)

        duration = time.time() - start_time
        logger.info(
            f'{request.method} {request.path} - '
            f'{response.status_code} - {duration:.2f}s'
        )

        return response


class CustomHeaderMiddleware:
    """Add custom headers to all responses."""

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)

        response['X-App-Version'] = '1.0.0'
        response['X-Request-ID'] = getattr(request, 'id', 'unknown')

        return response


class RequireHTTPSMiddleware:
    """Redirect HTTP to HTTPS."""

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if not request.is_secure() and not request.META.get('HTTP_X_FORWARDED_PROTO') == 'https':
            from django.http import HttpResponsePermanentRedirect
            url = request.build_absolute_uri(request.get_full_path())
            secure_url = url.replace('http://', 'https://')
            return HttpResponsePermanentRedirect(secure_url)

        return self.get_response(request)
1 file · python Explain with highlit

Custom middleware intercepts all requests and responses. I implement __init__ and __call__ methods. Middleware can modify requests before views, modify responses after views, or short-circuit entirely. Common uses include authentication, logging, CORS headers, or request timing. I can access request.user in middleware after AuthenticationMiddleware. Order in MIDDLEWARE setting matters—each wraps the next. For async support, I implement async middleware. This centralizes cross-cutting concerns.


Related snips

python
import os
import stat

for root, _dirs, files in os.walk('/etc'):
    for name in files:
        path = os.path.join(root, name)

Python security audit script for exposed risky filesystem state

python auditing host-security
by Kai Nakamura 1 tab
python
class Product(models.Model):
    name = models.CharField(max_length=200)
    slug = models.SlugField(blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    cost = models.DecimalField(max_digits=10, decimal_places=2)
    margin = models.DecimalField(max_digits=5, decimal_places=2, blank=True)

Django model signals vs overriding save

django python models
by Priya Sharma 2 tabs
python
from django.urls import path
from . import views

app_name = 'blog'

urlpatterns = [

Django URL namespacing and reverse lookups

django python urls
by Priya Sharma 3 tabs
python
import graphene
from graphene_django import DjangoObjectType
from blog.models import Post, Comment


class PostType(DjangoObjectType):

Django GraphQL with Graphene

django python graphql
by Priya Sharma 2 tabs
python
from django.db.models import Count, Avg, Sum, Q, F
from django.views.generic import TemplateView
from products.models import Product, Order, OrderItem


class DashboardView(TemplateView):

Django aggregation with annotate for statistics

django python database
by Priya Sharma 1 tab
python
from rest_framework import permissions


class IsOwner(permissions.BasePermission):
    """Allow only object owner to access."""

Django REST Framework permissions and authorization

django python rest
by Priya Sharma 2 tabs

Share this code

Here's the card — post it anywhere.

Django custom middleware for request/response modification — share card
Link copied