Django自定义--中间件
自定义中间件
-
process_request(self, request)
-
process_response(self, request, response)
-
process_view(self, request, view_func, view_args, view_kwargs)
-
process_exception(self, request, exception)
-
返回None,继续处理,返回HttpResponse,就结束
-
中间件配置:来时从上往下,走势从下往上
MIDDLEWARE_CLASSES = (
'middleware',
......
)
- 老版中间件
class CommonMiddleware(object):
def process_request(self, request):
return None
def process_response(self, request, response):
return response
- 新版中间件
class SimpleMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
# 调用 view 之前的代码
response = self.get_response(request)
# 调用 view 之后的代码
return response
- 兼容版
try:
from django.utils.deprecation import MiddlewareMixin # Django 1.10.x
except ImportError:
MiddlewareMixin = object # Django 1.4.x - Django 1.9.x
class SimpleMiddleware(MiddlewareMixin):
def process_request(self, request):
pass
def process_response(request, response):
pass