Skip to content

Instantly share code, notes, and snippets.

@nealtodd
Last active December 23, 2015 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nealtodd/6636280 to your computer and use it in GitHub Desktop.
Save nealtodd/6636280 to your computer and use it in GitHub Desktop.
Django management command: Take a fully qualified URL and show the resolved view (accounting for decorators on the view).
from textwrap import dedent
from urlparse import urlparse
from django.core.management.base import BaseCommand
from django.core.urlresolvers import resolve, Resolver404
class Command(BaseCommand):
"""
Take a fully qualified URL and show the resolved view
"""
args = "<url url ...>"
help = "Take a fully qualified URL and show the resolved view"
def handle(self, *args, **kwargs):
for arg in args:
self.stdout.write(dedent("""
path:\t%(url_path)s
view:\t%(view)s
file:\t%(file)s
name:\t%(url_name)s
kwargs:\t%(kwargs)s
args:\t%(args)s
""" % url2view(arg)))
def url2view(url):
url_path = urlparse(url).path
result = {'url_path': url_path}
try:
resolve_match = resolve(url_path)
except Resolver404:
result.update({'view': None, 'file': None, 'url_name': None, 'args': (), 'kwargs': {}})
else:
func = resolve_match.func
while True:
try:
closure = func.func_closure
except AttributeError:
break
if closure is None:
break
else:
func = closure[-1].cell_contents
result.update({
'view': '.'.join([func.__module__, func.__name__]),
'file': ' '.join([func.__code__.co_filename, 'line', str(func.__code__.co_firstlineno)]),
'url_name': resolve_match.url_name,
'args': resolve_match.args, 'kwargs': resolve_match.kwargs})
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment