项目开发中,需要查看检查所有的URL,一个一个url文件检查不方便,且有fbv的接口还有cbv的接口,不方便检查,于是写了个脚本获取所有接口url
from django.urls.resolvers import URLResolver, URLPattern
def recursion_urls(pre_namespace, pre_url, _urlpatterns, url_list: list):
"""
递归的去获取URL
:param pre_namespace: namespace前缀,以后用户拼接name
:param pre_url: url前缀,以后用于拼接url
:param _urlpatterns: 路由关系列表
:param url_list: 用于保存递归中获取的所有路由
:return:
"""
for item in _urlpatterns:
if isinstance(item, URLPattern): # 非路由分发
url = pre_url + str(item.pattern)
url_list.append(url.replace('^', '').replace('$', ''))
elif isinstance(item, URLResolver):
if pre_namespace:
if item.namespace:
namespace = '%s:%s' % (pre_namespace, item.namespace)
else:
namespace = pre_namespace
else:
if item.namespace:
namespace = item.namespace
else:
namespace = None
recursion_urls(namespace, pre_url + str(item.pattern), item.url_patterns, url_list)
def get_all_url_dict(_urlpatterns):
"""
获取项目中所有的URL
:return:
"""
res = []
recursion_urls(None, '/', _urlpatterns, res) # 递归去获取所有的路由
return res
from urls import urlpatterns # 从urls文件获取定义的urlpatterns
get_all_url_dict(urlpatterns) # 调用我们定义的方法,获取全部url
# 结果如:
Out[5]:
['/media/(?P.*)' ,
'/api/core_service/web/files/export/device_output/',
'/api/core_service/web/files/export/variable_output/',
]