Nâng ngoại lệ Http404
Thuộc phần Kiến thức cơ bản về Django trong hành trình Django của Coddy. Bài học 9 trên 23.
Mở /drinks/mocha/. Đường dẫn khớp, nhưng DRINKS["mocha"] gây ra KeyError, và trang web phản hồi với mã trạng thái 500, một lỗi máy chủ. Với khách truy cập, trang web của bạn trông như bị hỏng.
Phản hồi phù hợp là 404, không có trang đó. Một hàm xử lý cho biết điều này bằng cách phát sinh Http404. Quán cà phê có mười hai bàn, vì vậy hàm xử lý table có thể từ chối /table/40/:
from django.http import Http404, HttpResponse
def table(request, number):
if number > 12:
raise Http404(f"There is no table {number}")
...raise, không phải return: Http404 là một ngoại lệ, và Django chuyển nó thành trang 404 thông thường. Trả về HttpResponse("No such page") sẽ hiển thị dòng chữ đó với mã trạng thái 200, khiến trình duyệt và công cụ tìm kiếm hiểu rằng trang này tồn tại.
Thử thách
DễTrong menu/views.py, hãy để view drink gọi Http404 khi slug không có trong DRINKS.
Mở /drinks/mocha/ để xem thông báo 404, sau đó mở /drinks/latte/: trang này vẫn hoạt động.
Tự làm thử
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.")
Tất cả bài học trong Kiến thức cơ bản về Django
1Trang Django đầu tiên của bạn
Xin chào, DjangoTrang thứ hai2URL động
Bộ chuyển đổi đường dẫnTrang riêng cho mỗi loại đồ uốngChuỗi truy vấnNâng ngoại lệ Http404Tự luyện tập: Playground Django