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