python 确定完整的 Django url 配置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1828187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:08:43  来源:igfitidea点击:

Determine complete Django url configuration

pythondjangourl

提问by Michael

Is there a way to get the completedjango url configuration?

有没有办法获得完整的django url 配置?

For example Django's debugging 404 page does not show included url configs, so this is not the complete configuration.

例如 Django 的调试 404 页面不显示包含的 url 配置,所以这不是完整的配置。



Answer: Thanks to Alasdair, here is an example script:

:感谢 Alasdair,这是一个示例脚本:

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.urlpatterns)

采纳答案by Alasdair

Django is Python, so introspection is your friend.

Django 是 Python,所以内省是你的朋友。

In the shell, import urls. By looping through urls.urlpatterns, and drilling down through as many layers of included url configurations as possible, you can build the complete url configuration.

在 shell 中,导入urls. 通过循环遍历urls.urlpatterns,并尽可能多地向下钻取包含的 url 配置层,您可以构建完整的 url 配置。

import urls
urls.urlpatterns

The list urls.urlpatternscontains RegexURLPatternand RegexURLResolverobjects.

该列表urls.urlpatterns包含RegexURLPatternRegexURLResolver对象。

For a RegexURLPatternobject pyou can display the regular expression with

对于一个RegexURLPattern对象,p您可以显示正则表达式

p.regex.pattern

For a RegexURLResolverobject q, which represents an included url configuration, you can display the first part of the regular expression with

对于代表包含的 url 配置的RegexURLResolverobject q,您可以显示正则表达式的第一部分

q.regex.pattern

Then use

然后使用

q.url_patterns

which will return a further list of RegexURLResolverand RegexURLPatternobjects.

这将返回进一步的RegexURLResolverRegexURLPattern对象列表。

回答by Alan Viars

Django extensions provides a utility to do this as a manage.py command.

Django 扩展提供了一个实用程序来执行此操作作为 manage.py 命令。

pip install django-extensions

Then add django_extensionsto your INSTALLED_APPS in settings.py. then from the console just type the following

然后添加django_extensions到您的 INSTALLED_APPS 中settings.py。然后从控制台输入以下内容

python manage.py show_urls

回答by andy

At the risk of adding a "me too" answer, I am posting a modified version of the above submitted script that gives you a view listing all the URLs in the project, somewhat prettified and sorted alphabetically, and the views that they call. More of a developer tool than a production page.

冒着添加“我也是”答案的风险,我发布了上述提交脚本的修改版本,该脚本为您提供了一个列出项目中所有 URL 的视图,按字母顺序进行了一些美化和排序,以及它们调用的视图。与其说是生产页面,不如说是一种开发人员工具。

def all_urls_view(request):
    from your_site.urls import urlpatterns #this import should be inside the function to avoid an import loop
    nice_urls = get_urls(urlpatterns) #build the list of urls recursively and then sort it alphabetically
    return render(request, "yourapp/links.html", {"links":nice_urls})

def get_urls(raw_urls, nice_urls=[], urlbase=''):
    '''Recursively builds a list of all the urls in the current project and the name of their associated view'''
    from operator import itemgetter
    for entry in raw_urls:
        fullurl = (urlbase + entry.regex.pattern).replace('^','')
        if entry.callback: #if it points to a view
            viewname = entry.callback.func_name
            nice_urls.append({"pattern": fullurl, 
                  "location": viewname})
        else: #if it points to another urlconf, recur!
            get_urls(entry.url_patterns, nice_urls, fullurl)
    nice_urls = sorted(nice_urls, key=itemgetter('pattern')) #sort alphabetically
    return nice_urls

and the template:

和模板:

<ul>
{% for link in links %}
<li>
{{link.pattern}}   -----   {{link.location}}
</li>
{% endfor%}
</ul>

If you wanted to get real fancy you could render the list with input boxes for any of the regexes that take variables to pass to the view (again as a developer tool rather than production page).

如果您想获得真正的幻想,您可以为任何将变量传递给视图的正则表达式呈现带有输入框的列表(再次作为开发人员工具而不是生产页面)。

回答by abhillman

This question is a bit old, but I ran into the same problem and I thought I would discuss my solution. A given Django project obviously needs a means of knowing about all its URLs and needs to be able to do a couple things:

这个问题有点老了,但我遇到了同样的问题,我想我会讨论我的解决方案。一个给定的 Django 项目显然需要一种了解其所有 URL 的方法,并且需要能够做一些事情:

  1. map from a url -> view
  2. map from a named url -> url (then 1 is used to get the view)
  3. map from a view name -> url (then 1 is used to get the view)
  1. 从 url 映射 -> 查看
  2. 从命名的 url 映射 -> url(然后 1 用于获取视图)
  3. 从视图名称映射 -> url(然后 1 用于获取视图)

Django accomplishes this mostly through an object called a RegexURLResolver.

Django 主要通过一个名为RegexURLResolver.

  1. RegexURLResolver.resolve (map from a url -> view)
  2. RegexURLResolver.reverse
  1. RegexURLResolver.resolve(从 url 映射 -> 视图)
  2. RegexURLResolver.reverse

You can get your hands on one of these objects the following way:

您可以通过以下方式获得这些对象之一:

from my_proj import urls
from django.core.urlresolvers import get_resolver
resolver = get_resolver(urls)

Then, you can simply print out your urls the following way:

然后,您可以通过以下方式简单地打印出您的网址:

for view, regexes in resolver.reverse_dict.iteritems():
    print "%s: %s" % (view, regexes)

That said, Alasdair's solution is perfectly fine and has some advantages, as it prints out some what more nicely than this method. But knowing about and getting your hands on a RegexURLResolverobject is something nice to know about, especially if you are interested in Django internals.

也就是说,Alasdair 的解决方案非常好并且有一些优点,因为它打印出一些比这种方法更好的东西。但是了解并接触一个RegexURLResolver对象是一件很好的事情,特别是如果您对 Django 内部结构感兴趣的话。

回答by Niklas9

I have submitted a package (django-showurls) that adds this functionality to any Django project, it's a simple new management command that integrates well with manage.py:

我已经提交了一个包 (django-showurls),它将这个功能添加到任何 Django 项目中,它是一个简单的新管理命令,与 manage.py 集成良好:

$ python manage.py showurls
^admin/
  ^$
    ^login/$
    ^logout/$
.. etc ..

You can install it through pip:

你可以通过pip安装它:

pip install django-showurls

And then add it to your installed apps in your Django project settings.py file:

然后将其添加到 Django 项目 settings.py 文件中已安装的应用程序中:

INSTALLED_APPS = [
    ..
    'django_showurls',
    ..
]

And you're ready to go.

你准备好了。

More info here - https://github.com/Niklas9/django-showurls

更多信息在这里 - https://github.com/Niklas9/django-showurls

回答by shacker

The easiest way to get a complete list of registered URLs is to install contrib.admindocsthen check the "Views" section. Very easy to set up, and also gives you fully browsable docs on all of your template tags, models, etc.

获取已注册 URL 完整列表的最简单方法是安装contrib.admindocs,然后检查“视图”部分。非常容易设置,并且还为您提供了关于所有模板标签、模型等的完全可浏览的文档。

回答by Thierry Lam

Are you looking for the urls evaluated or not evaluated as shown in the DEBUG mode? For evaluated, django.contrib.sitemaps can help you there, otherwise it might involve some reverse engineering with Django's code.

您是否正在寻找已评估或未评估的 url,如 DEBUG 模式中所示?对于评估, django.contrib.sitemaps 可以帮助你,否则它可能涉及一些 Django 代码的逆向工程。

回答by Don Kirkby

When I tried the other answers here, I got this error:

当我在这里尝试其他答案时,出现此错误:

django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

django.core.exceptions.AppRegistryNotReady:应用程序尚未加载。

It looks like the problem comes from using django.contrib.admin.autodiscover()in my urls.py, so I can either comment that out, or load Django properly before dumping the URL's. Of course if I want to see the admin URL's in the mapping, I can't comment them out.

看起来问题来自django.contrib.admin.autodiscover()在 my 中使用urls.py,因此我可以将其注释掉,或者在转储 URL 之前正确加载 Django。当然,如果我想在映射中看到管理 URL,我不能将它们注释掉。

The way I found was to create a custom management commandthat dumps the urls.

我发现的方法是创建一个转储 url的自定义管理命令

# install this file in mysite/myapp/management/commands/urldump.py
from django.core.management.base import BaseCommand

from kive import urls


class Command(BaseCommand):
    help = "Dumps all URL's."

    def handle(self, *args, **options):
        self.show_urls(urls.urlpatterns)

    def show_urls(self, urllist, depth=0):
        for entry in urllist:
            print ' '.join(("  " * depth, entry.regex.pattern,
                            entry.callback and entry.callback.__module__ or '',
                            entry.callback and entry.callback.func_name or ''))
            if hasattr(entry, 'url_patterns'):
                self.show_urls(entry.url_patterns, depth + 1)

回答by Van Gale

If you are running Django in debug mode (have DEBUG = Truein your settings) and then type a non-existent URL you will get an error page listing the complete URL configuration.

如果您在调试模式下运行 Django(DEBUG = True在您的设置中有),然后输入一个不存在的 URL,您将看到一个错误页面,其中列出了完整的 URL 配置。