Django请求处理图
setting.py
MIDDLEWARE = [ 'mymiddlewares.AccessAuthMiddleWare', ] # 放行url,不进行登录验证 EXCLUDE_URL = [ "/login" ] # 用户名密码 USERS = [ ("username", "password") ]
自定义 mymiddleware.py
import re from django.shortcuts import redirect from django.utils.deprecation import MiddlewareMixin from settings import EXCLUDE_URL, USERS exclued_path = [re.compile(item) for item in EXCLUDE_URL] class AccessAuthMiddleWare(MiddlewareMixin): """ 访问控制 """ def process_request(self, request): # 放行 url_path = request.path for each in exclued_path: if re.match(each, url_path): return None # 验证 user = request.COOKIES.get('user') password = request.COOKIES.get('password') if (user, password) in USERS: return None else: return redirect('/login')