django middleware system - interceptor mode for request processing | Daoman PythonAI
#django middleware system - interceptor mode for request processing
📂 Stage: Part 2 - Advanced Features 🎯 Difficulty level: Intermediate ⏰ Estimated study time: 3-4 hours 🎒 Prerequisite knowledge: 视图系统与URL路由
Table of contents
Middleware concept and core structure
Django middleware is a global request/response interceptor framework - similar to adding a "security checkpoint" and "finishing station" to the request flow, which can add functions to the entire application without modifying the view/template.
The simplest middleware looks like this
Starting from Django 1.10, new style middleware is mainstream, and only needs to implement two core methods:
Middleware execution process and configuration
Onion model: core execution logic
The execution of the middleware is "onion structure"-the top one in the configuration list blocks the request first, and then blocks the response**:
Must be insettings.pyregister
Custom middleware not registered = useless, it is recommended to put it at the end of the list to avoid destroying the dependencies of the built-in middleware:
A quick overview of high-frequency built-in middleware
Django comes with 10+ built-in middleware by default. You don’t need to learn them all. Focus on mastering these 5:
1. SecurityMiddleware (the first stop for security interception)
Automatically add HTTPS, HSTS, XSS protection and other security headers, which must be retained in the production environment.
2. SessionMiddleware (session management)
Add to each request/responsesessionidCookie, the session data associated with the server, must be placed inAuthenticationMiddlewareFront.
3. CsrfViewMiddleware (anti-cross-site forgery)
Check the CSRF token of POST/PUT/PATCH requests to prevent malicious websites from stealing user identities.
4. AuthenticationMiddleware (identity injection)
Extract user information from the session and inject it intorequest.user(Certified to beUserObject, unauthenticated isAnonymousUser)。
5. CommonMiddleware (common function)
Automatically handles URL trailing slashes and APPEND_SLASH configuration. It is recommended to retain them in production environments.
Customized middleware in action
Choose two scenarios that will be used 100% in development:
1. Slow request/exception log middleware
Record the time consumption, status code, and IP of each request to facilitate troubleshooting:
2. Simple interface current limiting middleware
Prevent malicious interface brushing (simple version, recommended for production environments)django-ratelimitlibrary):
Execution sequence and best practices
Sequential red line (if you step on it, there will be problems)
- SessionMiddleware → AuthenticationMiddleware: Authentication relies on session
- SecurityMiddleware → All other middleware: Security first
- CommonMiddleware → CsrfViewMiddleware: Common processing relies on URL standardization
Performance and Security Best Practices
- Initialization is only done once:
__init__Load static resources and compile regular rules in it. Do not load it in__call__Check out the full list - Quick Return: Use regular or prefix judgment to intercept requests that do not need to be processed (such as static files) in advance.
- Don’t swallow exceptions: Unless there is clear processing logic, otherwise use
logger.errorcontinue to throw after - Put custom middleware last: avoid damaging the dependency chain of built-in middleware
Common pitfall troubleshooting
Pit 1: Custom middleware does not take effect
- Troubleshooting 1: Check
MIDDLEWAREIs the path to the list correct (note.Separate, not/) - Troubleshooting 2: Check whether the middleware class exists
__init__(self, get_response)and__call__(self, request)method - Troubleshooting 3: Check if there are any syntax errors (an error will be reported when starting django)
Pit 2: CSRF verification failed
- Troubleshooting 1: Check whether the form/request is included
{% csrf_token %}orX-CSRFTokenRequest header - Troubleshooting 2: Check whether the reverse proxy
HTTP_X_CSRFTOKENTransparently passed to django - Troubleshooting 3: Check
CSRF_TRUSTED_ORIGINSWhether to include the front-end domain name (the production environment must be HTTPS)
Pit 3:request.useryesAnonymousUser
- Troubleshooting 1: Check
SessionMiddlewareIs thereAuthenticationMiddlewareFront - Troubleshooting 2: Check whether the session has expired (
SESSION_COOKIE_AGE) - Troubleshooting 3: Check whether it passes
login()Method logged in
Summary of this chapter
In this chapter we have mastered the core knowledge of Django middleware:
- Concept: Global request/response interceptor, similar to the onion model
- Structure: The new style only needs
__init__and__call__, the old style usesMiddlewareMixin - Built-in middleware: Focus on Security, Session, CSRF, Authentication, and Common
- Practical: Wrote two common middlewares: logging and current limiting.
- ** Pitfalls **: Wrong order, wrong path, CSRF configuration issues
💡 Core Reminder: Middleware is a "double-edged sword" - it can quickly add global functions, but adding too much will slow down requests! Try to add only what is necessary.
🔗 Related tutorials
🏷️ Tags:django中间件 请求处理 拦截器 自定义中间件 django安全

