Http404 발생시키기
Coddy Django 여정의 Django 기초 섹션에 포함된 레슨. 23개 중 9번째.
/drinks/mocha/를 엽니다. 경로는 일치하지만 DRINKS["mocha"]에서 KeyError가 발생하고, 사이트는 서버 오류인 상태 코드 500으로 응답합니다. 방문자에게는 사이트가 고장 난 것처럼 보입니다.
올바른 응답은 해당 페이지가 없다는 404입니다. 뷰는 Http404를 발생시켜 이를 알립니다. 카페에는 테이블이 열두 개 있으므로 table 뷰에서 /table/40/ 요청을 거부할 수 있습니다.
from django.http import Http404, HttpResponse
def table(request, number):
if number > 12:
raise Http404(f"There is no table {number}")
...return이 아니라 raise입니다. Http404는 예외이며, Django는 이를 일반적인 404 페이지로 처리합니다. HttpResponse("No such page")를 반환하면 상태 코드 200으로 해당 문구가 표시되며, 이는 브라우저와 검색 엔진에 페이지가 존재한다고 알립니다.
챌린지
쉬움menu/views.py에서 slug가 DRINKS에 없으면 drink 뷰가 Http404를 발생시키도록 하세요.
404 메시지를 확인하려면 /drinks/mocha/를 연 다음, /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 플레이그라운드