문제

I have a two URL dispatches. One that catches words on http://domain.com/thisword, while the second dispatch is a sitemap on http://domain.com/sitemap.xml. The current code which does not work correct is:

urlpatterns = patterns('',
    url(ur'(?P<search_word>[ÆØÅæøåa-zA-Z]*)/?$', 'website.views.index_view', name='website_index'),
    url(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}),
)

So basically the first dispatch catches everything, including sitemap.xml. Is it possible to have multiple dispatches in following fashion?

도움이 되었습니까?

해결책

Good question. (Thanks for posting the full code here. Now I see what you are after, I think.) The easiest solution would be to reverse the patterns like this:

urlpatterns = patterns('',
    url(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}),
    url(ur'(?P<search_word>[ÆØÅæøåa-zA-Z]*)/?$', 'website.views.index_view', name='website_index'),
)

The dispatcher dispatches the moment it finds a match. So if a url matches r'^sitemap\.xml$ in the urlpatterns above, the dispatcher will not continue to the second pattern

다른 팁

In addition to Justin's answer, I want to add that in the general case, you can use negative lookahead patterns to prevent certain string from matching. http://docs.python.org/2/library/re.html#regular-expression-syntax

>>> re.search('(?P<search_word>^[\.a-zA-Z]*)/?$', 'sitemap.xml').group(0)
'sitemap.xml'
>>>

vs

>>> re.search('(?P<search_word>^(?!sitemap.xml)[\.a-zA-Z]*)/?$', 'sitemap.xml').group(0)
>>>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top