The Django Book 第八章 高级视图与url配置

本书网站链接

随着 Django 应用变得复杂,它的 URLconf 也在增长,并且维护这些导入可能使得管理变麻烦。

改进方式一 函数对象:

from django.conf.urls.defaults import *
**from mysite import views**

urlpatterns = patterns('',
    (r'^hello/$', **views.hello** ),
    (r'^time/$', **views.current_datetime** ),
    (r'^time/plus/(d{1,2})/$', **views.hours_ahead** ),
)

改进方式二 字符串:

from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'^hello/$', **'mysite.views.hello'** ),
    (r'^time/$', **'mysite.views.current_datetime'** ),
    (r'^time/plus/(d{1,2})/$', **'mysite.views.hours_ahead'** ),
)
# 注意视图名前后的引号

改进方式三 提取公共前缀:

from django.conf.urls.defaults import *

urlpatterns = patterns(**'mysite.views'** ,
    (r'^hello/$', **'hello'** ),
    (r'^time/$', **'current_datetime'** ),
    (r'^time/plus/(d{1,2})/$', **'hours_ahead'** ),
)

使用多个视图前缀:

旧的:
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'^hello/$', 'mysite.views.hello'),
    (r'^time/$', 'mysite.views.current_datetime'),
    (r'^time/plus/(\d{1,2})/$', 'mysite.views.hours_ahead'),
    (r'^tag/(\w+)/$', 'weblog.views.tag'),
)

新的:
from django.conf.urls.defaults import *

urlpatterns = patterns('mysite.views',
    (r'^hello/$', 'hello'),
    (r'^time/$', 'current_datetime'),
    (r'^time/plus/(\d{1,2})/$', 'hours_ahead'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(\w+)/$', 'tag'),
)

调试模式下的特例:

from django.conf import settings
from django.conf.urls.defaults import *
from mysite import views

urlpatterns = patterns('',
    (r'^$', views.homepage),
    (r'^(\d{4})/([a‐z]{3})/$', views.archive_month),
)
if settings.DEBUG:
    urlpatterns += patterns('',
        (r'^debuginfo/$', views.debug),
    )

使用命名组,url中传递命名的参数:
在 Python 正则表达式中,命名的正则表达式组的语法是 (?Ppattern) ,这里 name 是组的名字,而pattern 是匹配的某个模式。

# 使用无名组的 URLconf 的例子
from django.conf.urls.defaults import *
from mysite import views
urlpatterns = patterns('',
    (r'^articles/(\d{4})/$', views.year_archive),
    (r'^articles/(\d{4})/(\d{2})/$', views.month_archive),
)

# 使用命名组进行了重写
from django.conf.urls.defaults import *
from mysite import views
urlpatterns = patterns('',
    (r'^articles/(?P\d{4})/$', views.year_archive),
    (r'^articles/(?P\d{4})/(?P\d{2})/$', views.month_archive),
)

# 例如,如果不带命名组,请求 /articles/2006/03/ 将会等同于这样的函数调用:
month_archive(request, '2006', '03')
# 而带命名组,同样的请求就会变成这样的函数调用:
month_archive(request, year='2006', month='03')

需要注意的是如果在URLconf中使用命名组,那么命名组和非命名组是不能同时存在于同一个URLconf的模式中的。
具体地,以下是URLconf解释器有关正则表达式中命名组和 非命名组所遵循的算法:

1.如果有任何命名的组,Django会忽略非命名组而直接使用命名组。
2.否则,Django会把所有非命名组以位置参数的形式传递。
3.在以上的两种情况,Django同时会以关键字参数的方式传递一些额外参数。

额外参数


P113
下面是几节额外参数在实际工程中的应用:

一、创建通用视图
原视图:

# urls.py
from django.conf.urls.defaults import *
from mysite import views
urlpatterns = patterns('',
    (r'^events/$', views.event_list),
    (r'^blog/entries/$', views.entry_list),
)

# views.py
from django.shortcuts import render_to_response
from mysite.models import Event, BlogEntry
def event_list(request):
    obj_list = Event.objects.all()
    return render_to_response('mysite/event_list.html', {'event_list': obj_list})
def entry_list(request):
    obj_list = BlogEntry.objects.all()
    return render_to_response('mysite/blogentry_list.html', {'entry_list': obj_list})

改进后视图:

# urls.py
from django.conf.urls.defaults import *
from mysite import models, views
urlpatterns = patterns('',
    (r'^events/$', views.object_list, {'model': models.Event}),
    (r'^blog/entries/$', views.object_list, {'model': models.BlogEntry}),
)

# views.py
from django.shortcuts import render_to_response
def object_list(request, model):
    obj_list = model.objects.all()
    template_name = 'mysite/%s_list.html' % model.__name__.lower()
    return render_to_response(template_name, {'object_list': obj_list})

重点:了解捕捉值和额外参数之间的优先级 额外的选项

当冲突出现的时候,额外URLconf参数优先于捕捉值。 也就是说,如果URLconf捕捉到的一个命名组变量和一个额外URLconf参数包含的变量同名时,额外URLconf参数的值会被使用。

例如,下面这个URLconf:

from django.conf.urls.defaults import *
from mysite import views
urlpatterns = patterns('',
    (r'^mydata/(?P\d+)/$', views.my_view, {'id': 3}),
)

这里,正则表达式和额外字典都包含了一个 id 。硬编码的(额外字典的) id 将优先使用。 就是说任何请求(比如, /mydata/2/ 或者 /mydata/432432/ )都会作 id 设置为 3 对待,不管URL里面能捕捉到什么样的值。

使用缺省视图参数:

# urls.py
from django.conf.urls.defaults import *
from mysite import views

urlpatterns = patterns('',
    (r'^blog/$', views.page),
    (r'^blog/page(?P\d+)/$', views.page),
)
# views.py
def page(request, **num='1'**):
# Output the appropriate page of blog entries, according to num.
# ...

URLconf解析顺序:从顶向下的顺序,碰到合适就停止

从URL中捕获文本:

举个例子,在这行URLConf中:

(r'^articles/(?P\d{4})/$', views.year_archive),

尽管 \d{4} 将只匹配整数的字符串,但是参数 year 是作为字符串传至 views.year_archive() 的,而不是整型。

包装视图函数:
原视图:

def my_view1(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/accounts/login/')
    # ...
    return render_to_response('template1.html')
def my_view2(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/accounts/login/')
    # ...
    return render_to_response('template2.html')
def my_view3(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/accounts/login/')
    # ...
    return render_to_response('template3.html')

改进视图:

# views.py
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

# urls.py
from django.conf.urls.defaults import *
from mysite.views import requires_login, my_view1, my_view2, my_view3
urlpatterns = patterns('',
    (r'^view1/$', requires_login(my_view1)),
    (r'^view2/$', requires_login(my_view2)),
    (r'^view3/$', requires_login(my_view3)),
)

重要:包含其他URLconf:

# URLconf root 
from django.conf.urls.defaults import *
urlpatterns = patterns('',
    (r'^weblog/', include('mysite.blog.urls')),
    (r'^photos/', include('mysite.photos.urls')),
    (r'^about/$', 'mysite.views.about'),
)

# URLconf mysite.blog.urls
from django.conf.urls.defaults import *
urlpatterns = patterns('',
    (r'^(\d\d\d\d)/$', 'mysite.blog.views.year_detail'),
    (r'^(\d\d\d\d)/(\d\d)/$', 'mysite.blog.views.month_detail'),
)

捕获的参数如何和include()协同工作:

一个被包含的URLconf接收任何来自parent URLconfs的被捕获的参数,比如:

# root urls.py

from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'^(?P\w+)/blog/', include('foo.urls.blog')),
)

# foo/urls/blog.py

from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'^$', 'foo.views.blog_index'),
    (r'^archive/$', 'foo.views.blog_archive'),
)
#在这个例子中,被捕获的 username 变量将传递给被包含的 URLconf,
#进而传递给那个URLconf中的 每一个 视图函数。

额外的URLconf如何和include()协同工作

第一个:
# urls.py
from django.conf.urls.defaults import *
urlpatterns = patterns('',
    (r'^blog/', include('inner'), {'blogid': 3}),
)
# inner.py
from django.conf.urls.defaults import *
urlpatterns = patterns('',
    (r'^archive/$', 'mysite.views.archive'),
    (r'^about/$', 'mysite.views.about'),
    (r'^rss/$', 'mysite.views.rss'),
)

第二个
# urls.py
from django.conf.urls.defaults import *
urlpatterns = patterns('',
    (r'^blog/', include('inner')),
)
# inner.py
from django.conf.urls.defaults import *
urlpatterns = patterns('',
    (r'^archive/$', 'mysite.views.archive', {'blogid': 3}),
    (r'^about/$', 'mysite.views.about', {'blogid': 3}),
    (r'^rss/$', 'mysite.views.rss', {'blogid': 3}),
)

你可能感兴趣的:(The Django Book 第八章 高级视图与url配置)