Multiple url dispatches with Regex

徘徊边缘 提交于 2019-12-11 00:27:42

问题


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


来源:https://stackoverflow.com/questions/22335622/multiple-url-dispatches-with-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!