Skip to content

Instantly share code, notes, and snippets.

@davidbody
Last active August 31, 2019 17:30
Show Gist options
  • Save davidbody/853f924fec90b0f119d684ac568d2c3f to your computer and use it in GitHub Desktop.
Save davidbody/853f924fec90b0f119d684ac568d2c3f to your computer and use it in GitHub Desktop.
# project/management/commands/showurls.py
# Put a __init__.py file in project/management/ and project/management/commands/
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.urls import URLPattern, URLResolver
class Command(BaseCommand):
help = 'Shows all urls for the current project'
# Based on https://stackoverflow.com/a/54531546
def list_urls(self, lis, acc=None):
if acc is None:
acc = []
if not lis:
return
l = lis[0]
if isinstance(l, URLPattern):
yield acc + [str(l.pattern)]
elif isinstance(l, URLResolver):
yield from self.list_urls(l.url_patterns, acc + [str(l.pattern)])
yield from self.list_urls(lis[1:], acc)
def handle(self, *args, **options):
urlconf = __import__(settings.ROOT_URLCONF, {}, {}, [''])
for p in self.list_urls(urlconf.urlpatterns):
self.stdout.write(repr(p))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment