Django web框架之权限管理二

Posted Pythia丶陌乐

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django web框架之权限管理二相关的知识,希望对你有一定的参考价值。

1. login登录

def login(request):
    if request.method=="GET":
        return render(request,‘login.html‘)
    else:
        username=request.POST.get(‘user‘)
        password=request.POST.get(‘pwd‘)
        user=models.User.objects.filter(username=username,password=password).first()
        if user:
            init_permission(user,request)
            return redirect(‘/index/‘)
        else:
            return redirect(‘/login/‘)

2. init_permission(user,request)定制Session

from django.conf import settings

def init_permission(user,request):
  # 取数据 permission_list = user.roles.values( ‘permission__id‘, ‘permission__title‘, ‘permission__url‘, ‘permission__code‘, ‘permission__menu_group‘, ‘permission__group_id‘, ‘permission__group__caption‘, ‘permission__group__menu_id‘, ‘permission__group__menu__title‘, ).distinct() current_url = request.path_info # 过滤权限相关的 result = {} # 用户所有的操作代码和可访问的url地址——权限相关 for item in permission_list: group_id=item[‘permission__group_id‘] code = item[‘permission__code‘] url=item[‘permission__url‘] if group_id in result: result[group_id][‘codes‘].append(code) result[group_id][‘urls‘].append(url) else: result[group_id]={ ‘codes‘:[code,], ‘urls‘:[url,], }    # Session中添加字典 request.session[settings.PERMISSION_URL_DICT_KEY] = result # 过滤菜单相关的 menu_list = [] for item in permission_list: msg = { ‘id‘: item[‘permission__id‘], ‘title‘: item[‘permission__title‘], ‘url‘: item[‘permission__url‘], ‘menu_gp_id‘: item[‘permission__menu_group‘], ‘menu_id‘: item[‘permission__group__menu_id‘], ‘menu_title‘: item[‘permission__group__menu__title‘], } menu_list.append(msg)    # Session中添加字典  request.session[settings.PERMISSION_MENU_KEY]=menu_list

3. setting配置

PERMISSION_URL_DICT_KEY=‘permission_url_dict‘   # 权限url数据
PERMISSION_MENU_KEY=‘permission_menu_dict‘      # 菜单字典数据

4. 创建中间件

路径:E:\permission80\rbac\middleware\rbac.py  

import re
from django.conf import settings
from django.shortcuts import redirect,render,HttpResponse

class MiddlewareMixin(object):
    def __init__(self, get_response=None):
        self.get_response = get_response
        super(MiddlewareMixin, self).__init__()

    def __call__(self, request):
        response = None
        if hasattr(self, ‘process_request‘):
            response = self.process_request(request)
        if not response:
            response = self.get_response(request)
        if hasattr(self, ‘process_response‘):
            response = self.process_response(request, response)
        return response
# 继承父类MiddlewareMixin方法
class RbacMiddleware(MiddlewareMixin):
    def process_request(self,request):
        current_url=request.path_info  # 取到用户方法的路径信息:譬如 /index/,/userinfo/
     # 判断用户访问的路径是否在白名单中
        for url in settings.VALID_URL:
            regax="^{0}$".format(url)
       # 如果匹配成功停止匹配,None继续往后面执行其他中间件,如果没有则直接到url路由规则中匹配,(/index/ ,views.index) if re.match(regax,current_url): return None      # 从Session中取到权限数据,用户权限下的路径 permission_dict=request.session.get(settings.PERMISSION_URL_DICT_KEY)
     # 如果没有则跳转到登录路径 if not permission_dict: return redirect(‘/login/‘) flag=False for group_id,code_url_dic in permission_dict.items(): for db_url in code_url_dic[‘urls‘]: regax="^{0}$".format(db_url)
          # 匹配当前用户权限的路径是哪一个路径 if re.match(regax,current_url):
            # 给request中添加一个字典,values对应用户访问的权限下的codes代码:譬如 add list edit request.permission_code_list=code_url_dic[‘codes‘] flag=True break if flag: break if not flag: return HttpResponse(‘无权访问‘)

5. setting配置中间件

# 白名单
VALID_URL=[
    ‘/login/‘,
    ‘/logoff/‘,
    ‘/index/‘,
    ‘/test/‘,
    ‘/admin.*‘,
]

# 加入中间件列表中
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‘,
    ‘rbac.middleware.rbac.RbacMiddleware‘,
]

6. 自定义模板

路径:E:\permission80\rbac\templatetags\rbactag.py

a. 首先创建模板目录templatetags,名称必须一样

import re

from django.conf import settings
from django.template import Library

register = Library()

# 引用html文件tag.html
@register.inclusion_tag(‘tag.html‘)
def menu_html(request):
    # 通过request取到定制session中的菜单数据
    permission_menu = request.session[settings.PERMISSION_MENU_KEY]
    current_url = request.path_info
    menu_dict = {}
    for item in permission_menu:
       # 判断组内菜单是否在menu_dict中
        if not item[‘menu_gp_id‘]:
            menu_dict[item[‘menu_id‘]] = item

    for item in permission_menu:
        regax = "^{0}$".format(item[‘url‘])
       # 匹配用户访问的路径是menu_dict中哪一个,给访问的路径添加一条actvie活动匹配
        if re.match(regax, current_url):
            menu_gp_id = item[‘menu_id‘]
            if menu_gp_id:
               # 菜单组添加active
                menu_dict[menu_gp_id][‘active‘] = True
            else:
                # 组内菜单列表添加
                menu_dict[item[‘id‘]][‘active‘] = True

    result = {}
    for item in menu_dict.values():
        active = item.get(‘active‘)
        menu_id = item[‘menu_id‘]
        if menu_id in result:
            result[menu_id][‘children‘].append({‘title‘: item[‘title‘], ‘url‘: item[‘url‘], ‘active‘: active})
            if active:
                result[menu_id][‘active‘] = True
        else:
            result[menu_id] = {
                ‘menu_id‘: item[‘menu_id‘],
                ‘menu_title‘: item[‘menu_title‘],
                ‘active‘: active,
                ‘children‘: [
                    {‘title‘: item[‘title‘], ‘url‘: item[‘url‘], ‘active‘: active}
                ]
            }

    return {‘menu_dict‘: result}
    

  

  

  

 

  






以上是关于Django web框架之权限管理二的主要内容,如果未能解决你的问题,请参考以下文章

2020Python修炼记web框架之 权限管理+Auth模块

Web框架之Django_02基本操作(Django项目启动配置数据库连接orm增删改查)

Python Web框架之Django初探

Python之web框架Django

开源web框架django知识总结

web框架之--Django基础入门