python / intermediate
Snippet
Custom Middleware for Restricting HTTP Request Methods
Django middleware components intercept requests before they reach views. Implementing method inspection in callable middleware provides central application security enforcement against forbidden HTTP verbs.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
from typing import Callablefrom django.http import HttpRequest, HttpResponse, HttpResponseNotAllowedclass RestrictHttpMethodsMiddleware:def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]) -> None:self.get_response = get_responseself.disallowed_methods = {"TRACE", "CONNECT"}def __call__(self, request: HttpRequest) -> HttpResponse:if request.method in self.disallowed_methods:return HttpResponseNotAllowed(list(self.disallowed_methods))return self.get_response(request)
django
Breakdown
1
class RestrictHttpMethodsMiddleware:
Declares a class-based Django middleware using the standardCallable structure.
2
def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]) -> None:
Initializes the middleware instance receiving the next handler in the request chain.
3
def __call__(self, request: HttpRequest) -> HttpResponse:
Drives per-request execution when the request travels through the middleware stack.
4
if request.method in self.disallowed_methods:
Checks whether the incoming request HTTP verb matches restricted operations like TRACE or CONNECT.
5
return HttpResponseNotAllowed(list(self.disallowed_methods))
Short-circuits request handling and responds with an HTTP 405 error if an illegal method is used.