1. settings
WHITE_REGEX_URL_LIST = [ "/register/", "/send/sms/", "/login/", "/image/code/", "/index/", ]
2. 中间件
from django.utils.deprecation import MiddlewareMixin from wed import models from django.db.models import settings from django.shortcuts import redirect class AuthMiddleware(MiddlewareMixin): def process_request(self, request): user_id = request.session.get('user_id', 0) user_obj = models.UserInfo.objects.filter(id=user_id).first() request.tracer = user_obj # 白名单 """ 1. 获取当用户访问的URL 2. 检查URL是否在白名单中,如果再则可以继续向后访问,如果不在则进行判断是否已登录 """
# 获取访问者的url if request.path_info in settings.WHITE_REGEX_URL_LIST: return if not request.tracer: return redirect('login')
3. settings配置
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', ...... 'wed.middleware.auth.AuthMiddleware', ]