# 导入中间件
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import redirect
# 继承MiddlewareMixin
class LoginMiddleWare(MiddlewareMixin):
# 进路由对应的方法之前
def process_request(self, request):
# 正常就返回None
if request.path in ["/login/", "get_img"]:
return None
if not request.user.id:
return redirect("/login/")
Request预处理函数: process_request(self, request)
View预处理函数: process_view(self, request, callback, callback_args,callback_kwargs)
Template模版渲染函数:process_template_response()
Exception后处理函数:process_exception(self, request, exception)
process_exception() 应当返回None或HttpResponse对象。
Response后处理函数:process_response(self, request, response)
# 在settings中的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',
"app01.utils.middlewares.LoginMiddleWare",
]