programing tip

완전한 Django URL 구성 결정

itbloger 2020. 10. 8. 07:47
반응형

완전한 Django URL 구성 결정


완전한 장고 URL 구성 을 얻는 방법이 있습니까?

예를 들어 Django의 디버깅 404 페이지에는 포함 된 URL 구성이 표시되지 않으므로 이것이 완전한 구성이 아닙니다.


답변 : 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)

Django는 Python이므로 내성은 당신의 친구입니다.

셸에서 urls. 을 반복 urls.urlpatterns하고 포함 된 URL 구성의 가능한 한 많은 레이어를 드릴 다운하여 완전한 URL 구성을 구축 할 수 있습니다.

import urls
urls.urlpatterns

목록 urls.urlpatterns에는 RegexURLPatternRegexURLResolver개체 가 포함 됩니다.

A의 RegexURLPattern객체 p당신과 함께 정규 표현식을 표시 할 수 있습니다

p.regex.pattern

A의 RegexURLResolver객체 q는 포함 된 URL 구성을 나타냅니다, 당신은 정규 표현식과의 첫 부분을 표시 할 수 있습니다

q.regex.pattern

그런 다음

q.url_patterns

추가 RegexURLResolverRegexURLPattern객체 목록을 반환 합니다.


Django 확장은 manage.py 명령으로이를 수행하는 유틸리티를 제공합니다.

pip install django-extensions

그런 다음 django_extensionsINSTALLED_APPS에 settings.py. 그런 다음 콘솔에서 다음을 입력하십시오.

python manage.py show_urls

"me too"답변을 추가 할 위험을 감수하면서 프로젝트의 모든 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

및 템플릿 :

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

정말 멋지게 만들고 싶다면 변수를 뷰로 전달하는 정규식에 대한 입력 상자로 목록을 렌더링 할 수 있습니다 (다시 프로덕션 페이지가 아닌 개발자 도구로).


이 질문은 조금 오래되었지만 동일한 문제가 발생하여 해결책에 대해 논의 할 것이라고 생각했습니다. 주어진 Django 프로젝트는 분명히 모든 URL에 대해 알 수있는 수단이 필요하며 몇 가지 작업을 수행 할 수 있어야합니다.

  1. URL에서지도->보기
  2. 명명 된 url-> url의지도 (1은보기를 가져 오는 데 사용됨)
  3. 보기 이름-> URL에서지도 (보기를 가져 오는 데 1이 사용됨)

Django는 주로 RegexURLResolver.

  1. RegexURLResolver.resolve (URL->보기에서 매핑)
  2. RegexURLResolver.reverse

다음과 같은 방법으로 이러한 개체 중 하나를 손에 넣을 수 있습니다.

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

그런 다음 다음과 같은 방법으로 URL을 간단히 인쇄 할 수 있습니다.

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 RegexURLResolver object is something nice to know about, especially if you are interested in Django internals.


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:

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

You can install it through pip:

pip install django-showurls

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

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

And you're ready to go.

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


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


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.


When I tried the other answers here, 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)

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

참고URL : https://stackoverflow.com/questions/1828187/determine-complete-django-url-configuration

반응형