在上章中,time视图中,页面的内容,日期和时间是动态的,但是URL是静态的。
在多数动态Web应用中,URL中会包含参数,影页面的输出。
比如,班级中会给每一位同学分配一个URL,例如/stu/01/和/stu/22.
现在我们想让/time/page/1/页面显示一个小时后的日期,/time/page/2/页面显示两个小时后的日期,/time/page/3/页面显示三个小时后的日期。
那么这样写是错的:
urlpatterns = [
url(r'^time/$', datetime_),
url(r'^time/page/1/$', one_hour_ahead),
url(r'^time/page/2/$', two_hours_ahead),
url(r'^time/page/3/$', three_hours_ahead),
]
这样不仅要重复编写视图函数,而且只能预先定义的偏移范围,如果想要显示四个小时后的日期,就要重新编写一个视图,并且添加一行URL
因为URL模式是正则表达式,我们使用\d{1,2}模式匹配限制时间为99小时
:
urlpatterns = [
# ...
url(r'^time/page/(\d{1,2})/$', hours_ahead),
# ...
]
最终的URL配置如下:
from django.conf.urls import include, url
from django.contrib import admin
from mysite.views import hello, datetime_, hours_ahead
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^hello/$', hello),
url(r'^time/$', datetime_),
url(r'^time/page/(\d{1,2})/$', hours_ahead),
]
接下来写hours_ahead视图:
from django.http import Http404, HttpResponse
import datetime
def hours_ahead(request, offset):
try:
offset = int(offset)
except ValueError:
raise Http404()
dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
html = "In %s hour(s), it will be %s." % (offset, dt)
return HttpResponse(html)
offset(变量名)是 URL 模式中(\d{1,2})捕获的字符串。也就是时间的偏移量
首先调用 int() 处理 offset,把 Unicode 字符串转换成整数
如果传给 int() 函数的值不能转换成整数,如字符串,Python 会抛出 ValueError 异常。
如果遇到 ValueError 异常,抛出 django.http.Http404 异常,显示“Page not found”404 错误
URL 模式提供的输入验证虽然有用,但是并不严谨,因此我们要在视图函数中检查会不会抛出 ValueError 异常,以防意外。实现视图函数时最好别对参数做任何假设
访问
http://127.0.0.1:8000/time/page/3/,确认是否正常。