我有一个 django 项目,其中一些 API URL 存在于 urlpatterns 路径中的 urls.py 中,有些注册为路由器(rest_framework_extensions.routers)。
参考:
# urls.py
urlpatterns = [
path("healthcheck/", health_check_view, name="healthcheck"),
path("something/", include(router_something.urls))
]
这里,router_something 用于注册更多网址,例如:
router_something = DefaultRouter(trailing_slash=False)
router_something.register(r"path1/(?P<pk>\d+)/roles", SomeViewSet)
我想获取django项目中的所有url及其完整路径,例如:
healthcheck/
something/path1/1/roles # here i am replacing the placeholder pk with 1, this is something I can do
...
我发现这个解决方案有效:
def all_urls():
"""
Returns all the API routes
"""
urls = []
resolver = get_resolver(None)
for _, v in resolver.reverse_dict.items():
url_pattern = v and v[1]
if not url_pattern:
continue
url_pattern = re.sub(r"\\(.)", r"\1", url_pattern)
url_pattern = url_pattern and url_pattern.rstrip("$Z")
urls.append(url_pattern)
return list(set(urls))