django中的urls.py regex评估顺序是什么? [英] What is the urls.py regex evaluation order in django?

查看:55
本文介绍了django中的urls.py regex评估顺序是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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:

  1. Django确定要使用的根URLconf模块.通常,这是ROOT_URLCONF设置的值,但是如果传入HttpRequest对象具有一个称为urlconf的属性(由中间件设置)请求处理),其值将代替ROOT_URLCONF设置.
  2. Django加载该Python模块并查找变量urlpatterns.这应该是一个Python列表,格式为函数django.conf.urls.patterns().
  3. Django按顺序运行每个URL模式,并在与请求的URL匹配的第一个URL模式处停止.
  4. 一旦其中一个正则表达式匹配,Django就会导入并调用给定的视图,这是一个简单的Python函数.视图通过了HttpRequest作为其第一个参数以及正则表达式中捕获的所有值作为剩余的参数.
  5. 如果没有正则表达式匹配,或者在此过程中的任何时候引发异常,则Django都会调用相应的错误处理视图.请参阅下面的错误处理.

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

It said 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.

除非每个 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆