Django:如何查看urlpatterns列表?

我怎么能看到当前的urlpatterns“反向”正在寻找?

我在一个视图中调用了逆向,我认为这个论证应该成立,但实际上并不成立。有什么办法能让我知道为什么我的图案没有?

120548 次浏览

试试这个:

from django.urls import get_resolver
get_resolver().reverse_dict.keys()

或者如果你还在Django 1上。*:

from django.core.urlresolvers import get_resolver
get_resolver(None).reverse_dict.keys()

有一个我使用的插件:https://github.com/django-extensions/django-extensions,它有一个show_urls命令可以帮助。

如果你想要一个项目中所有url的列表,首先你需要安装django-extensions

您可以使用命令简单地安装。

pip install django-extensions

有关包的更多信息,请访问django-extensions

之后,在你的settings.py文件的INSTALLED_APPS中添加django_extensions,如下所示:

INSTALLED_APPS = (
...
'django_extensions',
...
)

urls . py的例子:

from django.urls import path, include
from . import views
from . import health_views


urlpatterns = [
path('get_url_info', views.get_url_func),
path('health', health_views.service_health_check),
path('service-session/status', views.service_session_status)
]


然后,在终端上运行任意命令

python manage.py show_urls

./manage.py show_urls

基于config urls.py的输出示例:

/get_url_info             django_app.views.get_url_func
/health                   django_app.health_views.service_health_check
/service-session/status   django_app.views.service_session_status

有关更多信息,您可以检查文档

activestate的上有一个食谱

import urls


def show_urls(urllist, depth=0):
for entry in urllist:
print("  " * depth, entry.regex.pattern)
if hasattr(entry, 'url_patterns'):
show_urls(entry.url_patterns, depth + 1)


show_urls(urls.url_patterns)
def get_resolved_urls(url_patterns):
url_patterns_resolved = []
for entry in url_patterns:
if hasattr(entry, 'url_patterns'):
url_patterns_resolved += get_resolved_urls(
entry.url_patterns)
else:
url_patterns_resolved.append(entry)
return url_patterns_resolved

在python中manage.py shell

import urls
get_resolved_urls(urls.urlpatterns)

我正在使用下面的命令:

(Python3 + Django 1.10)

from django.core.management import BaseCommand
from django.conf.urls import RegexURLPattern, RegexURLResolver
from django.core import urlresolvers




class Command(BaseCommand):


def add_arguments(self, parser):


pass


def handle(self, *args, **kwargs):


urls = urlresolvers.get_resolver()
all_urls = list()


def func_for_sorting(i):
if i.name is None:
i.name = ''
return i.name


def show_urls(urls):
for url in urls.url_patterns:
if isinstance(url, RegexURLResolver):
show_urls(url)
elif isinstance(url, RegexURLPattern):
all_urls.append(url)
show_urls(urls)


all_urls.sort(key=func_for_sorting, reverse=False)


print('-' * 100)
for url in all_urls:
print('| {0.regex.pattern:20} | {0.name:20} | {0.lookup_str:20} | {0.default_args} |'.format(url))
print('-' * 100)

用法:

./manage.py showurls

样例输出:

----------------------------------------------------------------------------------------------------
| ^(.+)/$              |                      | django.views.generic.base.RedirectView | {} |
| ^(.+)/$              |                      | django.views.generic.base.RedirectView | {} |
| ^(.+)/$              |                      | django.views.generic.base.RedirectView | {} |
| ^(.+)/$              |                      | django.views.generic.base.RedirectView | {} |
| ^(.+)/$              |                      | django.views.generic.base.RedirectView | {} |
| ^(.+)/$              |                      | django.views.generic.base.RedirectView | {} |
| ^static\/(?P<path>.*)$ |                      | django.contrib.staticfiles.views.serve | {} |
| ^media\/(?P<path>.*)$ |                      | django.views.static.serve | {'document_root': '/home/wlysenko/.virtualenvs/programmerHelper/project/media'} |
| ^(?P<app_label>polls|snippets|questions)/$ | app_list             | apps.core.admin.AdminSite.app_index | {} |
| ^(?P<app_label>activity|articles|badges|books|comments|flavours|forum|marks|newsletters|notifications|opinions|polls|questions|replies|snippets|solutions|tags|testing|users|utilities|visits)/reports/$ | app_reports          | apps.core.admin.AdminSite.reports_view | {} |
| ^(?P<app_label>activity|articles|badges|books|comments|flavours|forum|marks|newsletters|notifications|opinions|polls|questions|replies|snippets|solutions|tags|testing|users|utilities|visits)/statistics/$ | app_statistics       | apps.core.admin.AdminSite.statistics_view | {} |
| articles/(?P<slug>[-\w]+)/$ | article              | apps.articles.views.ArticleDetailView | {} |
| book/(?P<slug>[-_\w]+)/$ | book                 | apps.books.views.BookDetailView | {} |
| category/(?P<slug>[-_\w]+)/$ | category             | apps.utilities.views.CategoryDetailView | {} |
| create/$             | create               | apps.users.views.UserDetailView | {} |
| delete/$             | delete               | apps.users.views.UserDetailView | {} |
| detail/(?P<email>\w+@[-_\w]+.\w+)/$ | detail               | apps.users.views.UserDetailView | {} |
| snippet/(?P<slug>[-_\w]+)/$ | detail               | apps.snippets.views.SnippetDetailView | {} |
| (?P<contenttype_model_pk>\d+)/(?P<pks_separated_commas>[-,\w]*)/$ | export               | apps.export_import_models.views.ExportTemplateView | {} |
| download_preview/$   | export_preview_download | apps.export_import_models.views.ExportPreviewDownloadView | {} |
| ^$                   | import               | apps.export_import_models.views.ImportTemplateView | {} |
| result/$             | import_result        | apps.export_import_models.views.ImportResultTemplateView | {} |
| ^$                   | index                | django.contrib.admin.sites.AdminSite.index | {} |
| ^$                   | index                | apps.core.views.IndexView | {} |
| ^jsi18n/$            | javascript-catalog   | django.views.i18n.javascript_catalog | {'packages': ('your.app.package',)} |
| ^jsi18n/$            | jsi18n               | django.contrib.admin.sites.AdminSite.i18n_javascript | {} |
| level/(?P<slug>[-_\w]+)/$ | level                | apps.users.views.UserDetailView | {} |
| ^login/$             | login                | django.contrib.admin.sites.AdminSite.login | {} |
| ^logout/$            | logout               | django.contrib.admin.sites.AdminSite.logout | {} |
| newsletter/(?P<slug>[_\w]+)/$ | newsletter           | apps.newsletters.views.NewsletterDetailView | {} |
| newsletters/$        | newsletters          | apps.newsletters.views.NewslettersListView | {} |
| notification/(?P<account_email>[-\w]+@[-\w]+.\w+)/$ | notification         | apps.notifications.views.NotificationDetailView | {} |
| ^password_change/$   | password_change      | django.contrib.admin.sites.AdminSite.password_change | {} |
| ^password_change/done/$ | password_change_done | django.contrib.admin.sites.AdminSite.password_change_done | {} |
| ^image/(?P<height>\d+)x(?P<width>\d+)/$ | placeholder          | apps.core.views.PlaceholderView | {} |
| poll/(?P<pk>\w{8}-\w{4}-\w{4}-\w{4}-\w{12})/(?P<slug>[-\w]+)/$ | poll                 | apps.polls.views.PollDetailView | {} |
| ^add/$               | polls_choice_add     | django.contrib.admin.options.ModelAdmin.add_view | {} |
| ^(.+)/change/$       | polls_choice_change  | django.contrib.admin.options.ModelAdmin.change_view | {} |
| ^$                   | polls_choice_changelist | django.contrib.admin.options.ModelAdmin.changelist_view | {} |
| ^(.+)/delete/$       | polls_choice_delete  | django.contrib.admin.options.ModelAdmin.delete_view | {} |
| ^(.+)/history/$      | polls_choice_history | django.contrib.admin.options.ModelAdmin.history_view | {} |
| ^add/$               | polls_poll_add       | django.contrib.admin.options.ModelAdmin.add_view | {} |
| ^(.+)/change/$       | polls_poll_change    | django.contrib.admin.options.ModelAdmin.change_view | {} |
| ^$                   | polls_poll_changelist | django.contrib.admin.options.ModelAdmin.changelist_view | {} |
| ^(.+)/delete/$       | polls_poll_delete    | django.contrib.admin.options.ModelAdmin.delete_view | {} |
| ^(.+)/history/$      | polls_poll_history   | django.contrib.admin.options.ModelAdmin.history_view | {} |
| ^$                   | polls_vote_changelist | django.contrib.admin.options.ModelAdmin.changelist_view | {} |
| publisher/(?P<slug>[-_\w]+)/$ | publisher            | apps.books.views.PublisherDetailView | {} |
| question/(?P<slug>[-_\w]+)/$ | question             | apps.questions.views.QuestionDetailView | {} |
| ^add/$               | questions_answer_add | django.contrib.admin.options.ModelAdmin.add_view | {} |
| ^(.+)/change/$       | questions_answer_change | django.contrib.admin.options.ModelAdmin.change_view | {} |
| ^$                   | questions_answer_changelist | django.contrib.admin.options.ModelAdmin.changelist_view | {} |
| ^(.+)/delete/$       | questions_answer_delete | django.contrib.admin.options.ModelAdmin.delete_view | {} |
| ^(.+)/history/$      | questions_answer_history | django.contrib.admin.options.ModelAdmin.history_view | {} |
| ^add/$               | questions_question_add | django.contrib.admin.options.ModelAdmin.add_view | {} |
| ^(.+)/change/$       | questions_question_change | django.contrib.admin.options.ModelAdmin.change_view | {} |
| ^$                   | questions_question_changelist | django.contrib.admin.options.ModelAdmin.changelist_view | {} |
| ^(.+)/delete/$       | questions_question_delete | django.contrib.admin.options.ModelAdmin.delete_view | {} |
| ^(.+)/history/$      | questions_question_history | django.contrib.admin.options.ModelAdmin.history_view | {} |
| ^setlang/$           | set_language         | django.views.i18n.set_language | {} |
| ^add/$               | snippets_snippet_add | django.contrib.admin.options.ModelAdmin.add_view | {} |
| ^(.+)/change/$       | snippets_snippet_change | django.contrib.admin.options.ModelAdmin.change_view | {} |
| ^$                   | snippets_snippet_changelist | django.contrib.admin.options.ModelAdmin.changelist_view | {} |
| ^(.+)/delete/$       | snippets_snippet_delete | django.contrib.admin.options.ModelAdmin.delete_view | {} |
| ^(.+)/history/$      | snippets_snippet_history | django.contrib.admin.options.ModelAdmin.history_view | {} |
| solution/(?P<pk>\w{8}-\w{4}-\w{4}-\w{4}-\w{12})/(?P<slug>[-_\w]+)/$ | solution             | apps.solutions.views.SolutionDetailView | {} |
| suit/(?P<slug>[-\w]+)/$ | suit                 | apps.testing.views.SuitDetailView | {} |
| tag/(?P<name>[-_\w]+)/$ | tag                  | apps.tags.views.TagDetailView | {} |
| theme/(?P<slug>[-_\w]+)/$ | theme                | apps.forum.views.SectionDetailView | {} |
| topic/(?P<slug>[-_\w]+)/$ | topic                | apps.forum.views.TopicDetailView | {} |
| update/$             | update               | apps.users.views.UserDetailView | {} |
| ^r/(?P<content_type_id>\d+)/(?P<object_id>.+)/$ | view_on_site         | django.contrib.contenttypes.views.shortcut | {} |
| writer/(?P<slug>[-_\w]+)/$ | writer               | apps.books.views.WriterDetailView | {} |
----------------------------------------------------------------------------------------------------
我已经扩展了Seti的命令来显示命名空间,所有url部分,自动调整列宽度,按(命名空间,名称)排序: https://gist.github.com/andreif/263a3fa6e7c425297ffee09c25f66b20 < / p >
import sys
from django.core.management import BaseCommand
from django.conf.urls import RegexURLPattern, RegexURLResolver
from django.core import urlresolvers




def collect_urls(urls=None, namespace=None, prefix=None):
if urls is None:
urls = urlresolvers.get_resolver()
_collected = []
prefix = prefix or []
for x in urls.url_patterns:
if isinstance(x, RegexURLResolver):
_collected += collect_urls(x, namespace=x.namespace or namespace,
prefix=prefix + [x.regex.pattern])
elif isinstance(x, RegexURLPattern):
_collected.append({'namespace': namespace or '',
'name': x.name or '',
'pattern': prefix + [x.regex.pattern],
'lookup_str': x.lookup_str,
'default_args': dict(x.default_args)})
else:
raise NotImplementedError(repr(x))
return _collected




def show_urls():
all_urls = collect_urls()
all_urls.sort(key=lambda x: (x['namespace'], x['name']))


max_lengths = {}
for u in all_urls:
for k in ['pattern', 'default_args']:
u[k] = str(u[k])
for k, v in list(u.items())[:-1]:
# Skip app_list due to length (contains all app names)
if (u['namespace'], u['name'], k) == \
('admin', 'app_list', 'pattern'):
continue
max_lengths[k] = max(len(v), max_lengths.get(k, 0))


for u in all_urls:
sys.stdout.write(' | '.join(
('{:%d}' % max_lengths.get(k, len(v))).format(v)
for k, v in u.items()) + '\n')




class Command(BaseCommand):
def handle(self, *args, **kwargs):
show_urls()

注意:列顺序保存在Python 3.6中,在旧版本中需要使用OrderedDict

更新:带有OrderedDict的新版本现在存在于django-🍌的包中:https://github.com/5monkeys/django-bananas/blob/master/bananas/management/commands/show_urls.py

Django 1.11, Python 2.7.6

cd to_your_django_project

Python manage.py shell

然后粘贴以下代码。

from django.conf.urls import RegexURLPattern, RegexURLResolver
from django.core import urlresolvers
urls = urlresolvers.get_resolver()


def if_none(value):
if value:
return value
return ''


def print_urls(urls, parent_pattern=None):
for url in urls.url_patterns:
if isinstance(url, RegexURLResolver):
print_urls(url, if_none(parent_pattern) + url.regex.pattern)
elif isinstance(url, RegexURLPattern):
print(if_none(parent_pattern) + url.regex.pattern)


print_urls(urls)

样例输出:

^django-admin/^$
^django-admin/^login/$
^django-admin/^logout/$
^django-admin/^password_change/$
^django-admin/^password_change/done/$
^django-admin/^jsi18n/$
^django-admin/^r/(?P<content_type_id>\d+)/(?P<object_id>.+)/$
^django-admin/^wagtailimages/image/^$
^django-admin/^wagtailimages/image/^add/$
^django-admin/^wagtailimages/image/^(.+)/history/$
^django-admin/^wagtailimages/image/^(.+)/delete/$
^django-admin/^wagtailimages/image/^(.+)/change/$
^django-admin/^wagtailimages/image/^(.+)/$
...

只要输入一个你知道不存在的url,服务器就会返回一个错误消息,其中包含一个url模式列表。

例如,如果你在http://localhost:8000/something运行一个站点

输入

http://localhost:8000/something/blahNonsense,您的服务器将返回url搜索列表并显示在浏览器中

Django >= 2.0解决方案

我测试了这篇文章中的其他答案,它们要么不能与Django 2一起工作。X,不完整或太复杂。因此,以下是我的看法:

from django.conf import settings
from django.urls import URLPattern, URLResolver


urlconf = __import__(settings.ROOT_URLCONF, {}, {}, [''])


def list_urls(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 list_urls(l.url_patterns, acc + [str(l.pattern)])
yield from list_urls(lis[1:], acc)


for p in list_urls(urlconf.urlpatterns):
print(''.join(p))

该代码打印所有url,不像其他解决方案,它将打印完整的路径,而不仅仅是最后一个节点。例如:

admin/
admin/login/
admin/logout/
admin/password_change/
admin/password_change/done/
admin/jsi18n/
admin/r/<int:content_type_id>/<path:object_id>/
admin/auth/group/
admin/auth/group/add/
admin/auth/group/autocomplete/
admin/auth/group/<path:object_id>/history/
admin/auth/group/<path:object_id>/delete/
admin/auth/group/<path:object_id>/change/
admin/auth/group/<path:object_id>/
admin/auth/user/<id>/password/
admin/auth/user/
... etc, etc

django 2.0的极简解决方案

例如,如果你正在寻找installed_apps的第一个应用程序上的url,你可以像这样访问它:

from django.urls import get_resolver
from pprint import pprint


pprint(
get_resolver().url_patterns[0].url_patterns
)


你可以创建一个动态导入来收集项目中每个应用程序的所有URL模式,简单的方法如下:

def get_url_patterns():
import importlib
from django.apps import apps


list_of_all_url_patterns = list()
for name, app in apps.app_configs.items():
# you have a directory structure where you should be able to build the correct path
# my example shows that apps.[app_name].urls is where to look
mod_to_import = f'apps.{name}.urls'
try:
urls = getattr(importlib.import_module(mod_to_import), "urlpatterns")
list_of_all_url_patterns.extend(urls)
except ImportError as ex:
# is an app without urls
pass


return list_of_all_url_patterns


list_of_all_url_patterns = get_url_patterns()

我最近使用类似的方法创建了一个模板标记来显示活动导航链接。

from django.urls.resolvers import RegexPattern,RoutePattern
from your_main_app import urls


def get_urls():
url_list = []
for url in urls.urlpatterns:
url_list.append(url.pattern._regex) if isinstance(url.pattern, RegexPattern) else url_list.append(url.pattern._route)


return url_list

这里your_main_app是放置settings.py文件的应用程序名称

Django 1.8, Python 2.7+ 只需在Shell中运行这些命令。

.py shell并执行以下代码
from django.conf.urls import RegexURLPattern, RegexURLResolver
from django.core import urlresolvers
urls = urlresolvers.get_resolver(None)


def if_none(value):
if value:
return value
return ''


def print_urls(urls, parent_pattern=None):
for url in urls.url_patterns:
if isinstance(url, RegexURLResolver):
print_urls(url, if_none(parent_pattern) + url.regex.pattern)
elif isinstance(url, RegexURLPattern):
print(if_none(parent_pattern) + url.regex.pattern)


print_urls(urls)

在Django 3.0中,这很简单:

from django.urls import get_resolver
print(get_resolver().url_patterns)
< p >打印: [<URLPattern '' [name='home']>, <URLPattern '/testing' [name='another_url']>] < / p >

Django >= 2.0列表解决方案

领养自@CesarCanassa

from django.conf import settings
from django.urls import URLPattern, URLResolver


URLCONF = __import__(settings.ROOT_URLCONF, {}, {}, [''])


def list_urls(patterns, path=None):
""" recursive """
if not path:
path = []
result = []
for pattern in patterns:
if isinstance(pattern, URLPattern):
result.append(''.join(path) + str(pattern.pattern))
elif isinstance(pattern, URLResolver):
result += list_urls(pattern.url_patterns, path + [str(pattern.pattern)])
return result

又一次改编自凯撒·卡纳萨的发电机魔法。它可以被添加到你的应用程序yourapp/management/commands/dumpurls.py指示符中,这样它就可以作为management.py中的子命令访问。

注意:我添加了一行以确保它只过滤yourapp。如果需要其他url,则相应地更新或删除它。

作为management.py子命令

部署路径:yourapp/management/commands/dumpurls.py

from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django.urls import URLPattern, URLResolver


def list_urls(lis, acc=None):


if acc is None:
acc = []
if not lis:
return
l = lis[0]
if isinstance(l, URLPattern):
yield acc + [str(l.pattern),l.name]
elif isinstance(l, URLResolver):
yield from list_urls(l.url_patterns, acc + [str(l.pattern)])
yield from list_urls(lis[1:], acc)


class Command(BaseCommand):
help = 'List all URLs from the urlconf'


def handle(self, *args, **options):


urlconf = __import__(settings.ROOT_URLCONF, {}, {}, [''])


records, glen, nlen = [], 0, 0


for p in list_urls(urlconf.urlpatterns):
record = [''.join(p[:2]), p[2]]


# Update me, or add an argument
if record[0].startswith('yourapp'):


clen = len(record[0])
if clen > glen: glen = clen


clen = len(record[1])
if clen > nlen: nlen = clen
                

records.append(record)




self.stdout.write('{:-<{width}}'.format('',width=glen+nlen))
self.stdout.write('{:<{glen}}Name'.format('Path',glen=glen+4))
self.stdout.write('{:-<{width}}'.format('',width=glen+nlen))
for record in records:
self.stdout.write('{path:<{glen}}{name}'.format(path=record[0],
name=record[1],
glen=glen+4))
self.stdout.write('{:-<{width}}'.format('',width=glen+nlen))

样例输出

(env) django@dev:myproj~> ./manage.py dumpurls
-------------------------------------------------------------------------------------------------------
Path                                                                        Name
-------------------------------------------------------------------------------------------------------
yourapp/^api-key/$                                                          api-key-list
yourapp/^api-key\.(?P<format>[a-z0-9]+)/?$                                  api-key-list
yourapp/^attacks/$                                                          attack-list
yourapp/^attacks\.(?P<format>[a-z0-9]+)/?$                                  attack-list
yourapp/^attack-histories/$                                                 attackhistory-list
yourapp/^attack-histories\.(?P<format>[a-z0-9]+)/?$                         attackhistory-list
yourapp/^files/$                                                            file-list
yourapp/^files\.(?P<format>[a-z0-9]+)/?$                                    file-list
yourapp/^modules/$                                                          module-list
yourapp/^modules\.(?P<format>[a-z0-9]+)/?$                                  module-list

这里有一个快速而肮脏的黑客,只需获得你需要的信息,而不需要修改任何设置。

$ pip install django-extensions
$ python manage.py shell -c 'from django.core.management import call_command; from django_extensions.management.commands.show_urls import Command; call_command(Command())'

这是小猪在逃避@robert的回答。虽然是正确的,但我不想将django-extensions作为依赖项,即使它只是一秒钟。

import subprocces


res = subprocess.run(
'python manage.py show_urls',
capture_output=True,
shell=True,
)
url_list = [
line.split('\t')[0]
for line in res.stdout.decode().split('\n')
]

如果你正在使用DRF,你可以通过从router.get_urls()(在Django应用程序的urls.py文件中)打印urlpatterns来打印特定路由器的所有URL模式。

打开你的app urls.py并将print语句添加到文件底部,因此整个文件可能看起来像这样:

import pprint


from django.urls import include, path
from rest_framework import routers


from . import views


router = routers.DefaultRouter()
router.register(r"users", views.UserViewSet, basename="User")
router.register(r"auth", views.AuthenticationView, basename="Auth")
router.register(r"dummy", views.DummyViewSet, basename="Dummy")
router.register("surveys", views.SurveyViewSet, basename="survey")


urlpatterns = [
path("", include(router.urls)),
]


pprint.pprint(router.get_urls())

然后,这些图案会像这样打印出来:

[<URLPattern '^users/$' [name='User-list']>,
<URLPattern '^users\.(?P<format>[a-z0-9]+)/?$' [name='User-list']>,
<URLPattern '^users/admins/$' [name='User-admins']>,
<URLPattern '^users/admins\.(?P<format>[a-z0-9]+)/?$' [name='User-admins']>,
<URLPattern '^users/current/$' [name='User-current']>,
<URLPattern '^users/current\.(?P<format>[a-z0-9]+)/?$' [name='User-current']>,
<URLPattern '^users/(?P<pk>[^/.]+)/$' [name='User-detail']>,
<URLPattern '^users/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$' [name='User-detail']>,
<URLPattern '^auth/login/$' [name='Auth-login']>,
...
]