有没有类似“rake paths”的东西?在 Django 中?

发布于 2024-08-18 04:34:45 字数 590 浏览 5 评论 0原文

在 Rails 中,可以使用 rake 显示活动路线 (http://guides.rubyonrails.org/routing.html ):

$ rake routes
          users GET  /users          {:controller=>"users", :action=>"index"}
formatted_users GET  /users.:format  {:controller=>"users", :action=>"index"}
                POST /users          {:controller=>"users", :action=>"create"}
                POST /users.:format  {:controller=>"users", :action=>"create"}

django 是否有类似的工具/命令显示 URL 模式、模式名称(如果有)以及视图中的关联函数?

In rails, on can show the active routes with rake (http://guides.rubyonrails.org/routing.html):

$ rake routes
          users GET  /users          {:controller=>"users", :action=>"index"}
formatted_users GET  /users.:format  {:controller=>"users", :action=>"index"}
                POST /users          {:controller=>"users", :action=>"create"}
                POST /users.:format  {:controller=>"users", :action=>"create"}

Is there a similar tool/command for django showing the e.g. the URL pattern, the name of the pattern (if any) and the associated function in the views?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

哭了丶谁疼 2024-08-25 04:34:45

一项实验...

# appended to root urls.py

if __name__ == '__main__':

    from django.core.urlresolvers import RegexURLPattern, RegexURLResolver
    from django.utils.termcolors import colorize
    import os, sys

    sys.path.append(os.path.abspath('..'))
    os.environ['DJANGO_SETTINGS_MODULE'] = 'ialtr.settings'

    def traverse(url_patterns, prefix=''):
        for p in url_patterns:
            if isinstance(p, RegexURLPattern):
                composed = '%s%s' % (prefix, p.regex.pattern)
                composed = composed.replace('/^', '/')
                print colorize('\t%s' % (composed), fg='green'), '==> ',
                try:
                    sys.stdout.write(colorize('%s.' % p.callback.__module__,
                        fg='yellow'))
                    print p.callback.func_name
                except:
                    print p.callback.__class__.__name__
            if isinstance(p, RegexURLResolver):
                traverse(p.url_patterns, prefix=p.regex.pattern)

    traverse(urlpatterns)

现在,如果运行 python urls.py ...

$ python urls.py
    ^users/activate/complete/$ ==> django.views.generic.simple.direct_to_template
    ^users/activate/(?P<activation_key>\w+)/$ ==> registration.views.activate
    ^users/register/$ ==> registration.views.register
    ^users/register/complete/$ ==> django.views.generic.simple.direct_to_template
    ^users/register/closed/$ ==> django.views.generic.simple.direct_to_template
    ^login/$ ==> django.contrib.auth.views.MethodDecoratorAdaptor
    ^logout/$ ==> django.contrib.auth.views.logout
    ^password/change/$ ==> django.contrib.auth.views.MethodDecoratorAdaptor
    ^password/change/done/$ ==> django.contrib.auth.views.password_change_done
    ^password/reset/$ ==> django.contrib.auth.views.MethodDecoratorAdaptor
    ^password/reset/confirm/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$ ==> django.contrib.auth.views.password_reset_confirm
    ^password/reset/complete/$ ==> django.contrib.auth.views.password_reset_complete
    ^password/reset/done/$ ==> django.contrib.auth.views.password_reset_done
    ^ialt/applications/$ ==> ialt.views.applications
    ^static/(?P<path>.*)$ ==> django.views.static.serve
    ^$ ==> django.views.generic.simple.direct_to_template
    ^about/ ==> django.views.generic.simple.direct_to_template

An experiment ...

# appended to root urls.py

if __name__ == '__main__':

    from django.core.urlresolvers import RegexURLPattern, RegexURLResolver
    from django.utils.termcolors import colorize
    import os, sys

    sys.path.append(os.path.abspath('..'))
    os.environ['DJANGO_SETTINGS_MODULE'] = 'ialtr.settings'

    def traverse(url_patterns, prefix=''):
        for p in url_patterns:
            if isinstance(p, RegexURLPattern):
                composed = '%s%s' % (prefix, p.regex.pattern)
                composed = composed.replace('/^', '/')
                print colorize('\t%s' % (composed), fg='green'), '==> ',
                try:
                    sys.stdout.write(colorize('%s.' % p.callback.__module__,
                        fg='yellow'))
                    print p.callback.func_name
                except:
                    print p.callback.__class__.__name__
            if isinstance(p, RegexURLResolver):
                traverse(p.url_patterns, prefix=p.regex.pattern)

    traverse(urlpatterns)

Now, if one runs python urls.py ...

$ python urls.py
    ^users/activate/complete/$ ==> django.views.generic.simple.direct_to_template
    ^users/activate/(?P<activation_key>\w+)/$ ==> registration.views.activate
    ^users/register/$ ==> registration.views.register
    ^users/register/complete/$ ==> django.views.generic.simple.direct_to_template
    ^users/register/closed/$ ==> django.views.generic.simple.direct_to_template
    ^login/$ ==> django.contrib.auth.views.MethodDecoratorAdaptor
    ^logout/$ ==> django.contrib.auth.views.logout
    ^password/change/$ ==> django.contrib.auth.views.MethodDecoratorAdaptor
    ^password/change/done/$ ==> django.contrib.auth.views.password_change_done
    ^password/reset/$ ==> django.contrib.auth.views.MethodDecoratorAdaptor
    ^password/reset/confirm/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$ ==> django.contrib.auth.views.password_reset_confirm
    ^password/reset/complete/$ ==> django.contrib.auth.views.password_reset_complete
    ^password/reset/done/$ ==> django.contrib.auth.views.password_reset_done
    ^ialt/applications/$ ==> ialt.views.applications
    ^static/(?P<path>.*)$ ==> django.views.static.serve
    ^$ ==> django.views.generic.simple.direct_to_template
    ^about/ ==> django.views.generic.simple.direct_to_template
困倦 2024-08-25 04:34:45

当我尝试 miku 的回答时,出现以下错误:

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

看起来问题来自于在我的 urls.py 中使用 django.contrib.admin.autodiscover() ,所以我可以将其注释掉,或者在之前正确加载 Django转储 URL。当然,如果我想在映射中查看管理 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)

When I tried miku's answer, I got this error:

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

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.

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

# 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)
梦明 2024-08-25 04:34:45

admindocs 有类似的功能。但它不显示 URL 名称。

admindocs has a similar feature. But it doesn't display URL names.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文