from django.utils.deprecation import MiddlewareMixin
最后在settings.py文件里添加MIDDLEWARE配置项
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
# 目录名,文件名,类名
# 'middlewares.filterusermiddleware.MyMiddleWare',
'middlewares.filterusermiddleware.MyWareA',
'middlewares.filterusermiddleware.MyWareB',
'middlewares.filterusermiddleware.MyWareC',
]
from django.shortcuts import render
from django.utils.deprecation import MiddlewareMixin
class MyWareA(MiddlewareMixin):
def process_request(self, req):
print("中间件1的请求")
def process_response(self, req, response):
print("中间件1的返回")
return response
class MyWareB(MiddlewareMixin):
def process_request(self, req):
print("中间件2的请求")
def process_response(self, req, response):
print("中间件2的返回")
return response
class MyWareC(MiddlewareMixin):
def process_request(self, req):
print("中间件3的请求")
def process_response(self, req, response):
print("中间件3的返回")
return response
运行结果如下
ip白名单示例
from django.shortcuts import render
from django.utils.deprecation import MiddlewareMixin
class MyMiddleWare(MiddlewareMixin):
def process_request(self, req):
ip = req.META.get("REMOTE_ADDR")
# 白名单
white_ips = [
'61.144.96.111'
]
if ip in white_ips:
return render(req, 'home.html', {'data': []})
def home(req):
res = ['美女荷官']
return render(req, 'home.html', {'data': res})
{% for i in data %}
{{ i }}
{% empty %}
困
{% endfor %}
示例代码
class MyWareA(MiddlewareMixin):
def process_request(self, req):
print("中间件1的请求")
def process_response(self, req, response):
print("中间件1的返回")
return response
def process_view(self, req, callback, callback_args, callback_kwargs):
print("中间件1的view")
class MyWareB(MiddlewareMixin):
def process_request(self, req):
print("中间件2的请求")
def process_response(self, req, response):
print("中间件2的返回")
return response
def process_view(self, req, callback, callback_args, callback_kwargs):
print("中间件2的view")
class MyWareC(MiddlewareMixin):
def process_request(self, req):
print("中间件3的请求")
def process_response(self, req, response):
print("中间件3的返回")
return response
def process_view(self, req, callback, callback_args, callback_kwargs):
print("中间件3的view")
运行结果
其中request 是 HttpRequest 对象, response 是一个由Django view或者中间件返回的TemplateResponse 对象,process_template_response()在 view 使用 render 渲染一个模版对象完成之后被调用,它必须返回一个render 方法执行后的response对象。