自定义登录验证的中间件
中间件设置:about_middlewareday70\mymiddleware\s1.py
from django.conf import settings class CheckLogin(MiddlewareMixin): def process_request(self, request): # 判断当前访问的URL是不是在白名单中 white_urls = settings.WHITE_URLS if hasattr(settings, 'WHITE_URLS') else [] if request.path_info in white_urls: return None # 从请求的Session数据中取user user_id = request.session.get('user', None) if not user_id: # 没有登录跳转到登录页面 return redirect('/login/') else: user_obj = UserInfo.objects.get(id=user_id) request.user = user_obj
注册中间件
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', 'mymiddleware.s1.CheckLogin', #自定义中间件 ] # 定义中间件中放行的白名单 WHITE_URLS = ['/login/', ]