根據路飛學城luffycity.com 的crm項目修改的python
1 url入口:rbac/urls.pydjango
urlpatterns = [ ... # 批量操做權限 re_path(r'^multi/permissions/$', menu.multi_permissions, name='multi_permissions') # 自動發現項目中的全部URL ... ]
2 配置文件 settings函數
不用發現的url列表: AUTO_DISCOVER_EXCLUDE = [ '/admin/', '/login/', ]
3 自定發現url的組件:rbac/service/router.pyurl
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'mosson' import re from collections import OrderedDict from django.conf import settings from django.utils.module_loading import import_string from django.urls.resolvers import URLResolver, URLPattern # 路由分發:URLResolver。非路由分發:URLPattern def check_url_exclude(url): """ 查看被排除在外的url :param url: :return: """ for regex in settings.AUTO_DISCOVER_EXCLUDE: if re.match(regex, url): return True def recursion_urls(pre_namespace, pre_url, urlpatterns, url_ordered_dict): """ 遞歸獲取url :param pre_namespace: namespace 前綴 之後用於拼接name :param pre_url: url前綴,之後用於拼接url :param urlpatterns: 路由關係列表 :param url_ordered_dict: 用於保存遞歸中獲取的全部的url :return: """ for item in urlpatterns: if isinstance(item, URLPattern): #非路由分發 添加到字典url_ordered_dict中 if not item.name: continue if pre_namespace: name = "%s:%s" % (pre_namespace, item.name) else: name = item.name url = pre_url + str(item.pattern) # url = url.replace("^", "").replace("$", "") if check_url_exclude(url):# 判斷是否admin、login等咱們不須要的url,是的話直接跳過 continue url_ordered_dict[name] = {'name':name, 'url':url} elif isinstance(item, URLResolver): # 路由分發, 繼續遞歸 if pre_namespace: if item.namespace: namespace = f"{pre_namespace}:{item.namespace}" else: namespace = item.namespace else: if item.namespace: namespace = item.namespace else: namespace = None# 父級沒有namespace,本身也沒有 recursion_urls(namespace, pre_url+str(item.pattern), item.url_patterns, url_ordered_dict) def get_all_url(): """ 獲取全部的url :return: """ url_ordered_dict = OrderedDict() md = import_string(settings.ROOT_URLCONF) # 遞歸獲取全部的url recursion_urls(None, '/', md.urlpatterns, url_ordered_dict) return url_ordered_dict
4 視圖函數spa
from rbac.service.router import get_all_url_dict def multi_permissions(request): """ 批量操做權限 :param request: :return: """ # 獲取項目中全部的url all_url_dict = get_all_url_dict() for k, v in all_url_dict.items(): print(k, v) return HttpResponse('ok it')