最近想要获取Django所有的url以及url name,但搜了一下现有的教程都非常无语,明明非常简单的事,却搞出几十行代码,于是自己实现了一个非常简便的函数,分享出来。
先上代码:
from django.urls import get_urlconf, get_resolver, URLPattern, URLResolver
def get_all_url(resolver=None, pre=''):
if resolver is None:
resolver = get_resolver(get_urlconf())
for r in resolver.url_patterns:
if isinstance(r, URLPattern):
yield pre + str(r.pattern), r.name
if isinstance(r, URLResolver):
yield from get_all_url(r, pre +
str(r.pattern))
for url, name in get_all_url():
print("<'{}' [name='{}']>".format(url, name))
下面说下思路:
Django有个内置的函数 reverse
,其作用是通过name获取url,点进去后能看到他说通过 resolver
来获取url的。
于是我们输出resolver
,可以看到它是个URLResolver
类
In [1]: from django.urls import get_urlconf, get_resolver
In [2]: r=get_resolver(get_urlconf())
In [3]: print(r)
<URLResolver 'deeru.urls' (None:None) '^/'>
我们再看看URLResolver
类中有些什么方法
In [4]: dir(r)
Out[4]:
[ ... ,
'reverse',
'reverse_dict',
'url_patterns',
'urlconf_module',
'urlconf_name']
到这里没什么方便的方法,只能通过看名字与一个一个尝试来确定可以通过哪个函数来获取url,最终确定是 url_patterns
In [5]: r.url_patterns
Out[5]:
[<URLResolver <module 'jet.urls' from '/xx/jet/urls.py'> (jet:jet) 'jet/'>,
<URLResolver <module 'jet.dashboard.urls' from '/xx/jet/dashboard/urls.py'> (dashboard:jet-dashboard) 'jet/dashboard/'>,
<URLResolver <module 'froala_editor.urls' from '/xx/froala_editor/urls.py'> (None:None) 'froala_editor/'>,
<URLResolver <module 'captcha.urls' from '/xx/captcha/urls.py'> (None:None) 'captcha/'>,
<URLResolver <module 'deeru.urls_local' from 'DeerU/deeru/urls_local.py'> (None:None) ''>,
<URLPattern '^media/(?P<path>.*)$'>]
输出url_patterns
后它返回一个list,里面是一个URLResolver。
不过url_patterns
不止返回URLResolver,也会返回URLPattern。我们选一个list中的一个对象调用url_patterns
,不断递归调用就能看到URLPattern
In [10]: r.url_patterns[0].url_patterns
Out[10]:
[<URLPattern '^add_bookmark/$' [name='add_bookmark']>,
<URLPattern '^remove_bookmark/$' [name='remove_bookmark']>,
<URLPattern '^toggle_application_pin/$' [name='toggle_application_pin']>,
<URLPattern '^model_lookup/$' [name='model_lookup']>,
<URLPattern '^jsi18n/$' [name='jsi18n']>]
现在我们已经能手动输出所有url了,下面做的就是循环加递归输出url,也就是开头的函数。
Powered by Froala Editor
发表评论 (对文章评论)