程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Python] multi level menu list permission control

編輯:Python

In the development process, we often encounter multi-level menus , For example, the navigation bar 、 Category column, etc , It can even be an infinite menu .

The following is the role permission control , Control whether a menu can be viewed according to the database

1. Database related tables

CREATE TABLE `tb_menus` (
`menu_id` int(11) NOT NULL AUTO_INCREMENT,
`menu_name` varchar(200) NOT NULL,
`menu_level` int(11) NOT NULL,
`superior_menu_id` int(11) NOT NULL,
`menu_url` varchar(200) NOT NULL,
PRIMARY KEY (`menu_id`),
UNIQUE KEY `menu_name` (`menu_name`)
) ENGINE=InnoDB AUTO_INCREMENT=41 DEFAULT CHARSET=utf8
CREATE TABLE `tb_role_menu` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`menu_id` int(11) NOT NULL,
`role_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=119 DEFAULT CHARSET=utf8

tb_menus The table records each menu , The key message is the menu id And parent menus id,tb_role_menu The record is role_id And menu_id Correspondence of , That is, which role can access which menu

2. Code

Key code

# Here is Django Of ORM
def get_menu_tree(role_id):
menus = RoleMenu.objects.filter(role_id=role_id).values('menu_id')
menu_list = list(Menu.objects.filter(menu_id__in=menus).order_by("menu_id").values())
return generate_tree(menu_list, 0)
def generate_tree(menu_list, superior_menu_id, temp_list=None):
if temp_list is None:
temp_list = list()
tree = list()
for menu in menu_list:
if menu["menu_id"] in temp_list:
continue
if menu["superior_menu_id"] == superior_menu_id:
temp_list.append(menu["menu_id"])
menu["under_menu"] = generate_tree(menu_list, menu["menu_id"], temp_list)
tree.append(menu)
return tree

The resulting data structure is

res_menu = {

'menu_id': 1, 'menu_name': ' Authority role ', 'menu_level': 1, 'superior_menu_id': 0, 'menu_url': '',
'under_menu': [
{
},
# This list is the dictionary of the lower menu , Cycle all the time 
]
...
}

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved