#URL配置 # -*-coding:utf-8-*-from django.conf.urls.defaults import patterns, include, url# Uncomment the next two lines to enable the admin:from django.contrib import adminadmin.autodiscover()""" 整个框架关注的是:是否存在一个名为urlpatterns模块级别的变量 故而只要增加多个patterns对象即可,从而实现使用多个视图前缀,对视图模块进行分类管理维护"""urlpatterns = patterns('mysite.views', # 我们把hello视图函数当作对象处理,而不是调用它,这是python的一个重要特性,函数是一级对象(first-class objects) url(r'^hello/$', 'hello'), url(r'^currentdate/$', 'current_datetime'), url(r'time/\d{1,2}/$', 'current_datetime'), # 正则表达式利用括号从文本中提取数据,传入到视图函数 url(r'time/(\d{1,3})/$', 'time'), url(r'^render/$', 'render_template'), url(r'^accessDb/$', 'accessDb') )urlpatterns += patterns('', url(r'^admin/', include(admin.site.urls)))urlpatterns += patterns('mysite.books.views', url(r'^meta1/', 'request_meta'), url(r'^meta2/', 'request_meta_2'), # url(r'^search_form/', search_form), url(r'^search/', 'search') )urlpatterns += patterns('mysite.contact.views', url(r'^contact/', 'contact2') )
命名组URL配置实例(通过该方式可以以“关键字”方式传参到视图函数):
python函数传参方式:位置参数&关键字参数
def year_archive(request, year, month, day): """ 命名组语法:(?Pp) url(r'^year_archive/(?P \d{4})/(?P \d{1,2})/(?P \d{1,2})/$', 'year_archive') """ return HttpResponse('Now is %s-%s-%s' % (year, month, day))
URL短路逻辑:
#如果请求同时匹配多种模式,优先使用最顶层匹配到的视图函数 urlpatterns = patterns('',# ...('^auth/user/add/$', views.user_add_stage),('^([^/]+)/([^/]+)/add/$', views.add_stage),# ...)
视图包装:
urlpatterns += patterns('', url(r'^view1/', requires_login(my_view1)), url(r'^view2/', requires_login(my_view2)) )
def my_view1(request): return render_to_response('template1.html')def my_view2(request): return render_to_response('template2.html')def requires_login(view): def new_view(request, *args, **kwargs): if not request.user.is_authenticated(): return HttpResponseRedirect('/accounts/login/') return view(request, *args, **kwargs) return new_view
URL之include示例:
备注:捕获的参数(命名组传参)& 额外的URLconf如何与include()协同工作?
这些参数将传递给被包含的URLconf的每一行,