Django middleware (Middleware) is a piece of code that can intervene and change the request or response during Django's request/response processing. Middleware is a very powerful feature in the Django framework, which allows you to execute custom code before or after Django's view functions.
Middleware can be used for:
- Perform some request preprocessing.
- Perform some checks on requests, such as user authentication.
- Modify the request object.
- Modify the response object.
- Logs for requests and responses.
The working principle of Django middleware is that the middleware exists in the form of an ordered list, and Django calls the middleware in the order of this list.
Create middleware
To create a middleware, you need to define a Python class that contains several specific methods. The most commonly used methods are:
-
__init__
: Initialization method, called when middleware is instantiated. -
__call__
: This method will be called for each request, and you can write code to process the request here. -
process_view
: Called before the view function is called. -
process_exception
: Called when the view function throws an exception. -
process_template_response
: Called after the template response object is generated.
Example
Here is a simple middleware example that adds a custom HTTP header to the response of each request:
class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Code executed before the view function response = self.get_response(request) # Code executed after view function response['X-Custom-Header'] = 'Custom Value' return response
Using middleware
To use middleware, you need to add it to your Django project'sIn the file
MIDDLEWARE
In the list:
MIDDLEWARE = [ ... '', '', '', '', '', '', '', '', # Add your middleware ... ]
Make sure the order of middleware meets your business logic needs.
Things to note
- The execution order of middleware is important because it affects the processing flow of requests and responses.
- Use middleware with caution, as inappropriate use can lead to security or performance issues.
- Some middleware may modify the request or response object, which may affect the behavior of other middleware or view functions.
With middleware, you can add powerful features and flexibility to your Django apps.
Filter requests
In Django, middleware can be used to filter requests and log logs. This usually involves two aspects: request processing and response processing. Below I will introduce how to use middleware to implement these two functions.
Filter requests + log logs
Filtering a request usually refers to whether to allow the request to continue based on certain conditions before it reaches the view function. For example, you might want to implement a simple access control that allows only requests from a specific IP address to pass.
Here is a simple middleware example that checks the requested source IP address and rejects unauthorized IP:
class IPFilterMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Define a list of allowed IP addresses allowed_ips = ['192.168.1.1', '127.0.0.1'] # Get the requested IP address x_forwarded_for = ('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = ('REMOTE_ADDR') # Check if the IP is in the allowed list if ip not in allowed_ips: # If not in the allowed list, return 403 prohibited access from import HttpResponseForbidden return HttpResponseForbidden("You are not allowed to access this site.") # Continue to process the request response = self.get_response(request) return response
Logging
Logging is another common use of middleware. You can record the request details, such as the requested URL, method, IP address, etc., which is very useful for debugging and monitoring applications.
Here is a simple logging middleware example:
import datetime class LoggingMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Requested arrival time start_time = () # Process the request response = self.get_response(request) # The time when the request ends end_time = () # Logging logger = (__name__) ( f'Status Code: {response.status_code} ' f'| Method: {} ' f'| Path: {} ' f'| Time: {(end_time - start_time).total_seconds()}s' ) return response
Configure middleware
To use these middleware, you need to add them to your Django project'sIn the file
MIDDLEWARE
In the list:
MIDDLEWARE = [ ... '', '', '', '', '', '', '', '', # Add IP filter middleware '', # Add logging middleware ... ]
Make sure the order of middleware meets your business logic needs.
Things to note
- When filtering requests with middleware, make sure not to inadvertently block legitimate requests.
- When recording logs, be careful not to record sensitive information, such as passwords or personally identifiable information.
- Consider performance impact and avoid performing complex operations in middleware, which may increase the processing time of requests.
By using middleware reasonably, you can effectively control the requested access and record detailed log information, which is very helpful for maintaining and monitoring Django applications.
This is all about this article about Django Middleware Middleware. For more related content on Django Middleware, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!