引发 Http404
本课属于 Coddy Django 学习旅程的“Django 基础”单元。第 9 课,共 23 课。
打开 /drinks/mocha/。路由匹配成功,但 DRINKS["mocha"] 会引发 KeyError,网站返回状态码 500,也就是服务器错误。对访问者来说,你的网站看起来像是坏了。
正确的响应是 404,表示页面不存在。视图通过引发 Http404 来说明这一点。这家咖啡馆有 12 张桌子,所以 table 视图可以拒绝 /table/40/:
from django.http import Http404, HttpResponse
def table(request, number):
if number > 12:
raise Http404(f"There is no table {number}")
...用 raise,而不是 return:Http404 是一个异常,Django 会将它转换成常见的 404 页面。返回 HttpResponse("No such page") 会显示这些文字,但状态码是 200,这会告诉浏览器和搜索引擎该页面存在。
挑战
简单在 menu/views.py 中,让 drink 视图在 slug 不在 DRINKS 中时引发 Http404。
打开 /drinks/mocha/ 查看 404 错误消息,然后打开 /drinks/latte/:它仍然可以正常使用。
亲手试试
from django.http import HttpResponse
DRINKS = {
"espresso": {"name": "Espresso", "price": 2.5, "description": "A short, strong shot of coffee."},
"latte": {"name": "Latte", "price": 3.5, "description": "Espresso with lots of steamed milk."},
"flat-white": {"name": "Flat White", "price": 3.75, "description": "Espresso with a thin layer of silky milk."},
"hot-chocolate": {"name": "Hot Chocolate", "price": 3, "description": "Dark chocolate melted into warm milk."},
}
def home(request):
return HttpResponse("<h1>Welcome to Corner Café</h1><p>Fresh coffee and cake every day.</p>")
def about(request):
return HttpResponse("Corner Café opened in 2026.")
def hours(request):
return HttpResponse("Open every day from 8:00 to 18:00.")
def contact(request):
return HttpResponse("Write to us at hello@cornercafe.example.")
def table(request, number):
return HttpResponse(f"<h1>Table {number}</h1>")
def drink(request, slug):
item = DRINKS[slug]
return HttpResponse(f"<h1>{item['name']}</h1><p>{item['description']}</p>")
def order(request):
size = request.GET.get("size", "medium")
if size not in ["small", "medium", "large"]:
size = "medium"
return HttpResponse(f"You ordered a {size} coffee.")
Django 基础中的所有课
自己练习: Django 在线编辑器