In Django, how do I introspect application urls?
Question:
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?
Answers:
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)
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?
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)