FastAPI로 독서 기록 웹 서비스 만들기

코드 작성과 설명

· 2 views

[1] detail.html 삭제 버튼
할 일 1. 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" href="/books/{{ book.id }}/edit">수정</a>
        <form class="inline" action="/books/{{ book.id }}/delete" method="post">
            <button type="submit" class="danger">삭제</button>
        </form>
        <a class="button secondary" href="/">목록</a>
    </div>
</div>
</body>
</html>

▼ Explain

Path: templates/detail.html

        <form class="inline" action="/books/{{ book.id }}/delete" method="post">
버튼 하나만 있는 폼입니다. inline 모양이라 다른 버튼과 한 줄에 놓입니다.

            <button type="submit" class="danger">삭제</button>
누르면 POST /books/번호/delete 를 보냅니다. danger 모양이라 빨간 버튼입니다.


[2] main.py 삭제 함수
할 일 2. main.py 파일을 아래 내용과 같게 고칩니다.
굵은 줄이 이번에 바뀐 줄입니다.
아래는 이 단계까지 고친 파일 전체입니다.

파일 맨 아래에 book_delete를 더합니다.

▼ 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})


@app.get("/books/{book_id}/edit")
def book_edit(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)
    data = {"book_id": book.id, "title": book.title, "author": book.author, "memo": book.memo, "error": ""}
    return templates.TemplateResponse(request, "edit.html", data)


@app.post("/books/{book_id}")
def book_update(
    request: Request,
    book_id: int,
    title: str = Form(""),
    author: str = Form(""),
    memo: str = Form(""),
    db: Session = Depends(get_db),
):
    book = db.get(Book, book_id)
    if book is None:
        return not_found(request, book_id)
    title = title.strip()
    author = author.strip()
    memo = memo.strip()
    error = check_input(title, author, memo)
    if error:
        data = {"book_id": book_id, "title": title, "author": author, "memo": memo, "error": error}
        return templates.TemplateResponse(request, "edit.html", data)
    book.title = title
    book.author = author
    book.memo = memo
    db.commit()
    return RedirectResponse(f"/books/{book_id}", status_code=303)


@app.post("/books/{book_id}/delete")
def book_delete(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)
    db.delete(book)
    db.commit()
    return RedirectResponse("/", status_code=303)

▼ Explain

Path: main.py

@app.post("/books/{book_id}/delete")
삭제는 POST로만 받습니다.

    db.delete(book)
읽어 온 객체를 지울 대상으로 표시합니다.

    db.commit()
DELETE를 실행하고 확정합니다.

    return RedirectResponse("/", status_code=303)
지운 기록의 상세 화면은 더 없으므로 목록으로 보냅니다.


개념 정리: GET과 POST의 역할

GET은 화면을 가져오는 요청이고 POST는 서버의 데이터를 바꾸는 요청입니다. 브라우저와 검색 엔진은 링크(GET)를 미리 열어 보거나 다시 열 수 있으므로 GET 주소로 삭제가 되면 의도하지 않게 지워질 수 있습니다. 그래서 등록, 수정, 삭제는 모두 POST 폼으로 보냅니다.

실무에서는: 삭제 전에 한 번 더 묻기

이 책의 삭제 버튼은 누르면 바로 지웁니다. 실무 화면에서는 "정말 삭제할까요?" 확인 창을 띄우거나 바로 지우지 않고 삭제 표시만 남기는 방식을 많이 씁니다.

댓글

아직 댓글이 없습니다.