django中的urls.py regex评估顺序是什么? [英] What is the urls.py regex evaluation order in django?
问题描述
我在urls.py中遇到了正则表达式问题(我是django以及一般的正则表达式的初学者)
I was having some problems with the regex in urls.py (I am a beginner to django as well as regexes in general)
这是我的原始urls.py
Here is my original urls.py
url(r'^name/(?P<name>\w+)/$', 'course.views.name'),
url(r'^', 'course.views.index'),
我正在尝试使用以下方法访问它:
And I was trying to access it using this:
http://127.0.0.1:8000/name/blah/
我的视图如下:
def index(request):
return HttpResponse("Hello, sam. You're at the course index.")
def name(request, name):
return HttpResponse("Hello, %s. You're at the course index." % name)
我得到的结果是,无论我提供什么输入,我都会定期获得索引"功能,而不是名称"功能.我以为问题出在第一个正则表达式上.
The result I was getting was that for no matter what input I gave, I would regularly get the "index" function, and not the "name" function. I thought the problem was with the first regex.
但是后来,我将第二个更改为:
But then, I changed the the 2nd one to:
url(r'^$', 'course.views.index'),
这就是我想像的那样工作!
And THIS works just the way I figured it to work!
我知道"$"表示行尾,但是是否应该首先对第一个正则表达式求值?这些表达式的匹配顺序是什么?
I understand that "$" means end of line, but shouldnt the 1st regex have been evaluated first? What is the order in which these expressions are matched?
在每个url中添加一个"$"没什么大不了的,但是我想理解为什么我将它放在这里.
我正在使用Django1.4和Python 2.7
I am using Django1.4 and Python 2.7
推荐答案
阅读Django Django如何处理请求
How Django processes a request 当用户请求您的网页时由Django驱动的网站,这是系统遵循的算法确定要执行的Python代码: When a user requests a page from your
Django-powered site, this is the algorithm the system follows to
determine which Python code to execute: 说 It said 除非每个
查看全文
3.Django按顺序运行每个URL模式,并在与请求的URL匹配的第一个URL模式处停止.
因此,我认为这是一个错误.3. Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL.
So I think this is a bug.