Multiple url dispatches with Regex

2019-07-22 02:19发布

问题:

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?

回答1:

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



回答2:

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)
>>>