Permalink
Browse files

Added a 'show_urls' manage.py command, borrowed from django-extensions

  • Loading branch information...
slinkp committed Mar 26, 2012
1 parent 92f456e commit 078c80359e58359453e2f3f5d7c947918d6040d5
Showing with 140 additions and 0 deletions.
  1. +1 −0 ebpub/ebpub/db/management/commands/__init__.py
  2. +139 −0 ebpub/ebpub/db/management/commands/show_urls.py
@@ -0,0 +1 @@
+#
@@ -0,0 +1,139 @@
+# Taken from django-extensions.
+# https://github.com/django-extensions/
+# Copyright (c) 2007 Michael Trier
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
+
+from django.conf import settings
+from django.core.exceptions import ViewDoesNotExist
+from django.core.urlresolvers import RegexURLPattern, RegexURLResolver
+from django.core.management.base import BaseCommand
+from django.utils.translation import ugettext as _
+from optparse import make_option
+
+try:
+ # 2008-05-30 admindocs found in newforms-admin brand
+ from django.contrib.admindocs.views import simplify_regex
+except ImportError:
+ # fall back to trunk, pre-NFA merge
+ from django.contrib.admin.views.doc import simplify_regex
+import re
+
+
+#from django_extensions.management.color import color_style
+from django.core.management import color
+from django.utils import termcolors
+
+
+def color_style():
+ style = color.color_style()
+ if color.supports_color():
+ style.URL = termcolors.make_style(fg='green', opts=('bold',))
+ style.MODULE = termcolors.make_style(fg='yellow')
+ style.MODULE_NAME = termcolors.make_style(opts=('bold',))
+ style.URL_NAME = termcolors.make_style(fg='red')
+ return style
+
+def extract_views_from_urlpatterns(urlpatterns, base=''):
+ """
+ Return a list of views from a list of urlpatterns.
+
+ Each object in the returned list is a two-tuple: (view_func, regex)
+ """
+ views = []
+ for p in urlpatterns:
+ if isinstance(p, RegexURLPattern):
+ try:
+ views.append((p.callback, base + p.regex.pattern, p.name))
+ except ViewDoesNotExist:
+ continue
+ elif isinstance(p, RegexURLResolver):
+ try:
+ patterns = p.url_patterns
+ except ImportError:
+ continue
+ views.extend(extract_views_from_urlpatterns(patterns, base + p.regex.pattern))
+ elif hasattr(p, '_get_callback'):
+ try:
+ views.append((p._get_callback(), base + p.regex.pattern, p.name))
+ except ViewDoesNotExist:
+ continue
+ elif hasattr(p, 'url_patterns') or hasattr(p, '_get_url_patterns'):
+ try:
+ patterns = p.url_patterns
+ except ImportError:
+ continue
+ views.extend(extract_views_from_urlpatterns(patterns, base + p.regex.pattern))
+ else:
+ raise TypeError, _("%s does not appear to be a urlpattern object") % p
+ return views
+
+
+class _Command(BaseCommand):
+ options_list = BaseCommand.option_list + (
+ make_option("--unsorted", "-u", action="store_true", dest="unsorted",
+ help="Show urls unsorted but same order as found in url patterns"),
+ )
+
+ help = "Displays all of the url matching routes for the project."
+
+ requires_model_validation = True
+
+ def handle(self, *args, **options):
+ if args:
+ appname, = args
+
+ style = color_style()
+
+ if settings.ADMIN_FOR:
+ settings_modules = [__import__(m, {}, {}, ['']) for m in settings.ADMIN_FOR]
+ else:
+ settings_modules = [settings]
+
+ views = []
+ for settings_mod in settings_modules:
+ try:
+ urlconf = __import__(settings_mod.ROOT_URLCONF, {}, {}, [''])
+ except Exception, e:
+ if options.get('traceback', None):
+ import traceback
+ traceback.print_exc()
+ print style.ERROR("Error occurred while trying to load %s: %s" % (settings_mod.ROOT_URLCONF, str(e)))
+ continue
+ view_functions = extract_views_from_urlpatterns(urlconf.urlpatterns)
+ for (func, regex, url_name) in view_functions:
+ if hasattr(func, '__name__'):
+ func_name = func.__name__
+ elif hasattr(func, '__class__'):
+ func_name = '%s()' % func.__class__.__name__
+ else:
+ func_name = re.sub(r' at 0x[0-9a-f]+', '', repr(func))
+ views.append("%(url)s\t%(module)s.%(name)s\t%(url_name)s" % {'name': style.MODULE_NAME(func_name),
+ 'module': style.MODULE(func.__module__),
+ 'url_name': style.URL_NAME(url_name or ''),
+ 'url': style.URL(simplify_regex(regex))})
+ if not getattr(options, 'unsorted', False):
+ views = sorted(views)
+ return "\n".join([v for v in views]) + "\n"
+
+
+try:
+ from django.extensions.management.commands.show_urls import Command
+except ImportError:
+ Command = _Command

0 comments on commit 078c803

Please sign in to comment.