gpt4 book ai didi

python - django 中的 urls.py 正则表达式评估顺序是什么?

转载 作者:太空狗 更新时间:2023-10-29 21:06:05 25 4
gpt4 key购买 nike

我在 urls.py 中遇到了一些正则表达式的问题(我是 django 的初学者以及一般的正则表达式)

这是我原来的urls.py

url(r'^name/(?P<name>\w+)/$', 'course.views.name'),
url(r'^', 'course.views.index'),

我试图用这个访问它:

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)

我得到的结果是,无论我提供什么输入,我都会定期获得“索引”函数,而不是“名称”函数。我认为问题出在第一个正则表达式上。

但后来,我将第二个更改为:

url(r'^$', 'course.views.index'),

这正是我认为的工作方式!

我知道“$”表示行尾,但是不应该先评估第一个正则表达式吗?这些表达式的匹配顺序是什么?

在每个 url 中添加“$”并不是什么大不了的事,但我想了解为什么要将它放在那里。

我正在使用 Django1.4 和 Python 2.7

最佳答案

阅读 Django document

How Django processes a request

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:

  1. Django determines the root URLconf module to use. Ordinarily, this is the value of the ROOT_URLCONF setting, but if the incoming HttpRequest object has an attribute called urlconf (set by middleware request processing), its value will be used in place of the ROOT_URLCONF setting.
  2. Django loads that Python module and looks for the variable urlpatterns. This should be a Python list, in the format returned by the function django.conf.urls.patterns().
  3. Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL.
  4. Once one of the regexes matches, Django imports and calls the given view, which is a simple Python function. The view gets passed an HttpRequest as its first argument and any values captured in the regex as remaining arguments.
  5. If no regex matches, or if an exception is raised during any point in this process, Django invokes an appropriate error-handling view. See Error handling below.

它说 3。 Django 按顺序运行每个 URL 模式,并在第一个与请求的 URL 匹配的模式处停止。 所以我认为这是一个错误。

你应该在每个 url 模式中添加 $ 除非 Including other URLconfs

关于python - django 中的 urls.py 正则表达式评估顺序是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10878103/

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