实现功能:白名单,正则匹配权限
from django.utils.deprecation import MiddlewareMixin from django.shortcuts import redirect,HttpResponse import re class PermissionMiddleware(MiddlewareMixin): def process_request(self,request): # 获取当前用户访问的url current_path = request.path # 用户访问白名单 white_list = ['/login/','/register/','/index/','/admin/*'] for item in white_list: res = re.search(item,current_path) if res: return None # 先校验当前用户是否登录 if not request.session.get('username'): return redirect('/login') # 获取当前用户所有的权限 permission_list = request.session.get("permission_list") if permission_list: for permission in permission_list: permission = '^%s$'%permission res = re.search(permission,current_path) if res: return None return HttpResponse('没有权限')