gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:03:31 25 4
gpt4 key购买 nike

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

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

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

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

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

用 $ 检查字符串的结尾。如果包含模式将“thisdir/”从完整 url 中断开以首先检查该部分,并且我认为它一次检查每个字符串部分(因此“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>)这将匹配等于thisdir/ 的url由于终止 $ .因此,像 thisdir/foobar/ 这样的 url将不匹配并且永远不会被包含处理。

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

关于python - 为什么不在 Django 检查字符串结尾时包含 url 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31125084/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com