为什么不在 Django 检查字符串结尾时包含 url 正则表达式

Why don't include url regexes in django check for end of string

假设您有完整的 url 个 localhost:thisdir/callview/

我注意到在 urls.py 文件中,包含的命名空间写为:

(r'^thisdir/', include('thisdir.urls', namespace='thisdir)),

其中检查了开始字符串,但未检查结束字符串,并按以下方式完成视图调用:

(r'^callview/$', 'thisdir.views.index', name='myview')

用 $ 检查字符串的结尾。如果包含模式从完整的 url 中断开 "thisdir/" 以首先检查该部分,我认为它会一次检查每个字符串部分(所以 "thisdir/" 在字符串的末尾)为什么我从来没有看到 (r'^thisdir/$', ...)

谢谢

https://docs.djangoproject.com/en/1.8/topics/http/urls/

Note that the regular expressions in this example don’t have a $ (end-of-string match character) but do include a trailing slash. Whenever Django encounters include() (django.conf.urls.include()), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.

如果您使用 $ 终止包含,则该规则将不再匹配包含文件中的任何内容,因为它只会匹配以包含正则表达式结尾的 URL。

您从未看到它的原因是因为它会阻止 URL 包含的目的。

(r'^thisdir/$', <include>) 由于 $ 终止,这 匹配 url 等于 thisdir/。因此 url 如 thisdir/foobar/ 将不匹配并且永远不会被包含处理。

另一方面,如果您将 $ 排除在正则表达式之外,/thisdir/<anything> 将匹配正则表达式,因此可以由包含的 url 进一步处理。