In Django, how do I introspect application urls?

…衆ロ難τιáo~ 提交于 2019-12-11 12:36:10

问题


In bottle or flask I can do something like this:

for route in app.routes:
    description = route.callback.__doc__
    method = method

So I can loop through all url (routes) register for given application and see its callback function (view in Django jargon), accepted methods and so on.

I'm wondering if the same is possible with django. So I would like to get all urls for given app and all views that are linked to those urls. Is that can be done?


回答1:


You need to import urls module from project. urls.urlpatterns is what you are looking for. Try this function:

import urls # or from app import urls
def print_urls(patterns, indent=0):
    for u in patterns:
        if u.callback:
            print '-'*indent, u.regex.pattern, u.callback
        else:
            print '='*(indent+1), u.regex.pattern
            print_urls(u.url_patterns, indent+3)

print_urls(urls.urlpatterns)


来源:https://stackoverflow.com/questions/21733413/in-django-how-do-i-introspect-application-urls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!