[1] list.html 제목 링크
할 일 1. templates/list.html 파일을 아래 내용과 같게 고칩니다.
굵은 줄이 이번에 바뀐 줄입니다.
아래는 이 단계까지 고친 파일 전체입니다.
▼ Code
Path: templates/list.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>독서 기록장</title>
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<div class="container">
<h1>독서 기록장</h1>
<div class="toolbar">
<a class="button" href="/books/new">등록</a>
</div>
{% if books %}
<table>
<thead>
<tr>
<th>번호</th>
<th>제목</th>
<th>저자</th>
<th>등록일</th>
</tr>
</thead>
<tbody>
{% for book in books %}
<tr>
<td>{{ book.id }}</td>
<td><a href="/books/{{ book.id }}">{{ book.title }}</a></td>
<td>{{ book.author }}</td>
<td>{{ book.created_at.strftime("%Y-%m-%d %H:%M") }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p class="empty">기록이 없습니다.</p>
{% endif %}
</div>
</body>
</html>
▼ Explain
Path: templates/list.html
<td><a href="/books/{{ book.id }}">{{ book.title }}</a></td>
행마다 그 기록의 번호가 들어간 주소로 링크를 만듭니다.
[2] detail.html 상세 화면
할 일 2. templates/detail.html 파일을 새로 만들고 아래 내용을 모두 입력합니다.
▼ Code
Path: templates/detail.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>독서 기록 상세</title>
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<div class="container">
<h1>독서 기록 상세</h1>
<table>
<tr>
<th>번호</th>
<td>{{ book.id }}</td>
</tr>
<tr>
<th>제목</th>
<td>{{ book.title }}</td>
</tr>
<tr>
<th>저자</th>
<td>{{ book.author }}</td>
</tr>
<tr>
<th>메모</th>
<td class="memo">{{ book.memo }}</td>
</tr>
<tr>
<th>등록일</th>
<td>{{ book.created_at.strftime("%Y-%m-%d %H:%M") }}</td>
</tr>
</table>
<div class="actions">
<a class="button secondary" href="/">목록</a>
</div>
</div>
</body>
</html>
▼ Explain
Path: templates/detail.html
<td class="memo">{{ book.memo }}</td> memo 모양은 입력한 줄바꿈을 그대로 보여 줍니다. <a class="button secondary" href="/">목록</a> 회색 버튼으로 목록에 돌아갑니다. 수정과 삭제 버튼은 다음 장들에서 이 줄 위에 더합니다.
[3] error.html 오류 안내
할 일 3. templates/error.html 파일을 새로 만들고 아래 내용을 모두 입력합니다.
▼ Code
Path: templates/error.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>오류</title>
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<div class="container">
<h1>오류</h1>
<p class="error">{{ message }}</p>
<a class="button secondary" href="/">목록</a>
</div>
</body>
</html>
▼ Explain
Path: templates/error.html
<p class="error">{{ message }}</p>
함수가 넘긴 안내 문구를 빨간 글자로 보여 줍니다.
[4] main.py not_found와 상세 함수
할 일 4. main.py 파일을 아래 내용과 같게 고칩니다.
굵은 줄이 이번에 바뀐 줄입니다.
아래는 이 단계까지 고친 파일 전체입니다.
check_input 아래에 not_found를, book_create 아래에 book_detail을 더합니다.
▼ Code
Path: main.py
from fastapi import Depends, FastAPI, Form, Request
from fastapi.responses import RedirectResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from sqlalchemy import select
from sqlalchemy.orm import Session
from database import get_db
from models import Book
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
def check_input(title, author, memo):
if not title:
return "제목을 입력해 주세요."
if not author:
return "저자를 입력해 주세요."
if len(title) > 200 or len(author) > 100 or len(memo) > 1000:
return "입력한 글자가 너무 깁니다."
return ""
def not_found(request, book_id):
message = f"없는 기록입니다. id={book_id}"
return templates.TemplateResponse(request, "error.html", {"message": message}, status_code=404)
@app.get("/")
def book_list(request: Request, db: Session = Depends(get_db)):
books = db.scalars(select(Book).order_by(Book.id.desc())).all()
return templates.TemplateResponse(request, "list.html", {"books": books})
@app.get("/books/new")
def book_new(request: Request):
data = {"title": "", "author": "", "memo": "", "error": ""}
return templates.TemplateResponse(request, "form.html", data)
@app.post("/books")
def book_create(
request: Request,
title: str = Form(""),
author: str = Form(""),
memo: str = Form(""),
db: Session = Depends(get_db),
):
title = title.strip()
author = author.strip()
memo = memo.strip()
error = check_input(title, author, memo)
if error:
data = {"title": title, "author": author, "memo": memo, "error": error}
return templates.TemplateResponse(request, "form.html", data)
db.add(Book(title=title, author=author, memo=memo))
db.commit()
return RedirectResponse("/", status_code=303)
@app.get("/books/{book_id}")
def book_detail(request: Request, book_id: int, db: Session = Depends(get_db)):
book = db.get(Book, book_id)
if book is None:
return not_found(request, book_id)
return templates.TemplateResponse(request, "detail.html", {"book": book})
▼ Explain
Path: main.py
def not_found(request, book_id): 없는 번호일 때 보여 줄 응답을 만드는 함수입니다. 수정과 삭제에서도 씁니다. return templates.TemplateResponse(request, "error.html", {"message": message}, status_code=404) 화면은 error.html이고 응답 코드는 404입니다. @app.get("/books/{book_id}") 중괄호 부분은 경로 매개변수입니다. /books/1 이면 1이 book_id가 됩니다. def book_detail(request: Request, book_id: int, db: Session = Depends(get_db)): book_id: int 라고 적었으므로 FastAPI가 주소의 글자를 정수로 바꿔 넣습니다. 바꿀 수 없으면 함수를 부르지 않고 422를 돌려줍니다. book = db.get(Book, book_id) 기본 키로 한 건을 읽습니다. 없으면 None입니다. if book is None: 없는 번호면 404 안내를 돌려주고 함수를 끝냅니다.
개념 정리: 경로 매개변수와 타입 검사
주소 안에 {book_id}처럼 이름을 적으면 그 자리의 글자를 함수 매개변수로 받습니다. 매개변수에 int 같은 타입을 적으면 FastAPI가 바꿔 넣고 바꿀 수 없으면 422 응답과 함께 무엇이 틀렸는지 JSON으로 알려 줍니다. 함수 안에서 숫자인지 따로 검사하지 않아도 됩니다.
초보자가 자주 하는 실수
주소 순서
증상: /books/new 를 열면 등록 화면 대신 422 JSON이 보입니다.
원인: FastAPI는 위에 적은 주소부터 맞춰 봅니다. /books/{book_id}가 /books/new보다 위에 있으면 new를 book_id로 보고 정수로 바꾸다가 실패합니다.
고치는 법: @app.get("/books/new") 함수를 @app.get("/books/{book_id}") 함수보다 위에 둡니다. 이 책의 순서를 그대로 따르면 됩니다.
개인정보처리방침 · 이용약관