문제

꽤 표준 Django 앱이 있으며 각 URL을보기에 명시 적으로 매핑 할 필요가 없도록 URL 라우팅을 설정하는 방법이 궁금합니다.

예를 들어 다음 견해가 있다고 가정 해 봅시다. Project, Links, Profile, Contact. 나는 차라리 내가 없다 urlpatterns 이렇게 보인다 :

(r'^Project/$', 'mysite.app.views.project'),
(r'^Links/$', 'mysite.app.views.links'),
(r'^Profile/$', 'mysite.app.views.profile'),
(r'^Contact/$', 'mysite.app.views.contact'),

등등. ~ 안에 철론, 그것은 간단합니다.

map.connect(':controller/:action/:id')

그리고 올바른 컨트롤러와 기능을 자동으로 가져옵니다. Django에서 비슷한 것이 있습니까?

도움이 되었습니까?

해결책

mods = ('Project','Links','Profile','Contact')

urlpatterns = patterns('',
   *(('^%s/$'%n, 'mysite.app.views.%s'%n.lower()) for n in mods)
)

다른 팁

당신이 정말로 없다면 거대한 스타일의 관점에서 볼 때보기의 수, 명시 적으로 기록하는 것은 그리 나쁘지 않습니다.

그러나 접두사의 인수를 사용하여 예제를 단축 할 수 있습니다. patterns 기능:

urlpatterns = patterns('mysite.app.views',
    (r'^Project/$', 'project'),
    (r'^Links/$', 'links'),
    (r'^Profile/$', 'profile'),
    (r'^Contact/$', 'contact'),
)

이 라인을 따라 특수보기 기능을 사용할 수 있습니다.

def router(request, function, module):
    m =__import__(module, globals(), locals(), [function.lower()])
    try:
        return m.__dict__[function.lower()](request)
    except KeyError:
        raise Http404()

그리고 다음과 같은 urlconf :

(r'^(?P<function>.+)/$', router, {"module": 'mysite.app.views'}),

이 코드는 테스트되지 않았지만 일반적인 아이디어는 다음을 기억해야하더라도 작동해야합니다.

명시 적은 암시적인 것보다 낫습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top