[置顶] django快速获取项目所有的URL

时间:2022-10-17 10:52:35

django快速获取项目所有的URL

django1.10快速获取项目所有的URL列表,可以用于权限控制

函数如下:

import re
def get_url(urllist , parent='' , depth=0 , url_list=[] , url_dict={}):
for entry in urllist:
url = entry.regex.pattern
if re.search('\(' , url) :
continue
#过滤正则表达式的URL地址 url = url.replace(r'^' , '')
url = url.replace(r'$' , '')
url = url.replace(r'/' + '$' , '') if depth == 0:
if url in ['admin' , 'admin/' , 'auth' , 'auth/']:
continue
#过滤admin和auth等app if re.search('\/$' , url) :
url_list.append('/' + url)
else :
url_list.append('/' + parent + url) try :
url_dict['/'].append('/' + url)
except :
url_dict['/'] = []
url_dict['/'].append('/' + url)
else :
url_list.append('/' + parent + url)
try :
url_dict['/' + parent].append('/' + parent + url)
except :
url_dict['/' + parent] = []
url_dict['/' + parent].append('/' + parent + url) if hasattr(entry, 'url_patterns'):
get_url(entry.url_patterns , url , depth + 1) # url_dict = {'/basicdata/': ['/basicdata/provider/add', '/basicdata/provider/export', '/basicdata/provider/list', '/basicdata/provider/detail'], '/': ['/basicdata/', '/login.html']} # url_list = ['/basicdata/', '/basicdata/department/export', '/basicdata/department/list', '/basicdata/department/detail', '/basicdata/department/edit', '/login.html', '/index.html'] return url_dict

注意:

调用get_url函数获得清单,必须使用函数或者class来封装

def recreate(request):
from library.django.get_url import get_url
from lykops import urls
url_dict = get_url(urls.urlpatterns)
print(url_dict) return HttpResponseRedirect(reverse('list'))

然后修改urls.py

urlpatterns = [
......
url(r'^/recreate/', views.recreate, name="recreate"),
......
]

如果其他函数调用的话,报错AttributeError: module ‘lykops.urls’ has no attribute ‘urlpatterns’

  File "/opt/lykops/sysadmin/urls.py", line 5, in <module>
url(r'^app/add', views.App().add, name="add_app"),
File "/opt/lykops/sysadmin/views.py", line 76, in __init__
self.recreate()
File "/opt/lykops/sysadmin/views.py", line 79, in recreate
url_dict = get_allurl(urls.urlpatterns)
AttributeError: module 'lykops.urls' has no attribute 'urlpatterns'