python django

【django】自定义中间件权限认证

技术分享

systemime
2020-03-28
1 min

摘要.

# APP下,mymiddleware.py
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse,redirect,render
from django.urls import reverse

class PermissionAuth(MiddlewareMixin):
    def process_request(self.request):
        # 白名单
        white_list = [reverse('login'),]
        if request.path in white_list:
            return 
        
        is_login = request.session.get("is_login", None)
        if not is_login:
            return redirect("login")
        
        # 权限
        permission_list = request.session.get("permission_list")
        # 正则url处理
        for reg in permission_list:
            reg = r"^%s$" % reg['permission_url']  # 加入结束符$
            if re.match(reg, reguest_path):
                return 
        else:  # for else
            return HttpResponse("您不配...")

# setting.py中
MIDDLEWARE = [
	...
    # 加入
    'appname.mymiddeware.PerisionAuth',
]

上次编辑于: 2021/5/24 下午1:55:49