django url配置
一个干净、优雅的URL方案是一个高质量的Web应用程序的一个重要的细节。
1.django的请求过程
官网是这么说的:
- 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.
- 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().
- Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL.
- 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.
- 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.
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.命名组