Django通过视图名称获取urlpatterns正则表达式

时间:2014-08-07 08:20:47

标签: python django url

我不是在寻找from django.core.urlresolvers import reverse
我想做的是: 我有一个urlpattern:

urlpatterns = patterns('xxx.views',
    url(r'^search/$', 'resume_search', name='xxx_resume_search'),
    url(r'^recruit/manage/(?P<id>[0-9]+)$', 'recruit_manage', name='xxx_recruit_manage'),
)

我想做点什么

rr = reverse_regex('xxx_recruit_manage') 

rr将为'^recruit/manage/(?P<id>[0-9]+)$'

如果

urlpatterns = patterns('xxx.views',
    url(r'^search/$', 'resume_search', name='xxx_resume_search'),
    url(r'^recruit/manage/$', 'recruit_manage', name='xxx_recruit_manage'),
)
    url(r'^recruit/manage/(?P<id>[0-9]+)$', 'recruit_manage', name='xxx_recruit_manage'),
)

rr将是['^recruit/manage/$','^recruit/manage/(?P<id>[0-9]+)$']

我该怎么做?

1 个答案:

答案 0 :(得分:1)

urls.py就像任何其他模块一样,你可以导入它并查看它有什么。

以下内容非常简洁但可以展示API。

import myapp.urls as my_urls

regex_pattern = my_urls.urlpatterns[2].regex.pattern
>> ^recruit/manage/(?P<id>[0-9]+)

好一点

regex_object = filter(lambda x:'xxx_recruit_manage' == x.name, my_urls.urlpatterns)
>> [<RegexURLPattern recruit_manage ^recruit/manage/(?P<id>[0-9]+)$>]