django URL设计(URL dispatcher)

django  url配置

一个干净、优雅的URL方案是一个高质量的Web应用程序的一个重要的细节。

1.django的请求过程

官网是这么说的:

  1. Django determines the root URLconf module to use. Ordinarily, this is the value of theROOT_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 (or a class based view). 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.
1.django设置一个根urlconf,

2.python加载一个url配置模块。

3.django 去查找所有rul模式,并且当碰到相匹配的url地址停止。

4.根据url去查找views函数

5.如果没有匹配的,将返回一个错误


实例:

from django.conf.urls import patterns, url

urlpatterns = patterns('',
    url(r'^articles/2003/$', 'news.views.special_case_2003'),
    url(r'^articles/(\d{4})/$', 'news.views.year_archive'),
    url(r'^articles/(\d{4})/(\d{2})/$', 'news.views.month_archive'),
    url(r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'news.views.article_detail'),
)
注意:r是可选的,但是建议使用r来匹配,

/articles/2005/03/将匹配第三个,

/articles/ 2005/3 /不匹配任何URL模式,因为3比匹配,应该是03

/articles/2003/ 只匹配第一个,因为他是按照顺序来执行。当匹配后,静停止匹配。

/articles/2003将不匹配任何,因为他后面没有/

/articles/2003/03/03/将匹配最后的模式。

2.命名组


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值