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

코드 작성과 설명

· 1 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>
        <a class="button secondary" href="/">목록</a>
    </div>
</div>
</body>
</html>

▼ Explain

Path: templates/detail.html

        <a class="button" href="/books/{{ book.id }}/edit">수정</a>
이 기록의 수정 화면 주소로 가는 버튼입니다.


[2] edit.html 수정 폼
할 일 2. templates/edit.html 파일을 새로 만들고 아래 내용을 모두 입력합니다.

form.html과 같은 모양이고 제목, 보내는 주소, 아래쪽 버튼만 다릅니다.

▼ Code

Path: templates/edit.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>
    {% if error %}
    <p class="error">{{ error }}</p>
    {% endif %}
    <form action="/books/{{ book_id }}" method="post">
        <p>
            <label for="title">제목</label>
            <input id="title" type="text" name="title" value="{{ title }}" maxlength="200">
        </p>
        <p>
            <label for="author">저자</label>
            <input id="author" type="text" name="author" value="{{ author }}" maxlength="100">
        </p>
        <p>
            <label for="memo">메모</label>
            <textarea id="memo" name="memo" rows="5" maxlength="1000">{{ memo }}</textarea>
        </p>
        <div class="actions">
            <button type="submit">저장</button>
            <a class="button secondary" href="/books/{{ book_id }}">취소</a>
        </div>
    </form>
</div>
</body>
</html>

▼ Explain

Path: templates/edit.html

    <form action="/books/{{ book_id }}" method="post">
저장을 누르면 POST /books/번호 로 보냅니다. 번호는 함수가 넘긴 book_id입니다.

            <a class="button secondary" href="/books/{{ book_id }}">취소</a>
저장하지 않고 상세 화면으로 돌아갑니다.


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

book_detail 아래에 book_edit와 book_update를 더합니다.

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

▼ Explain

Path: main.py

@app.get("/books/{book_id}/edit")
수정 폼을 보여 주는 주소입니다.

    data = {"book_id": book.id, "title": book.title, "author": book.author, "memo": book.memo, "error": ""}
읽어 온 기록의 값을 폼에 채우도록 넘깁니다.

@app.post("/books/{book_id}")
수정 폼이 보낸 값을 받아 저장합니다. 같은 주소의 GET은 상세 화면이고 POST는 수정 저장입니다.

    book.title = title
객체의 속성을 바꾸면 세션이 바뀐 것을 기억합니다.

    db.commit()
바뀐 속성으로 UPDATE를 실행하고 확정합니다.

    return RedirectResponse(f"/books/{book_id}", status_code=303)
수정한 기록의 상세 화면으로 보냅니다.


개념 정리: 변경 감지

SQLAlchemy 세션은 db.get으로 읽어 온 객체를 기억합니다. 객체의 속성을 바꾼 뒤 commit하면 바뀐 컬럼만 골라 UPDATE 문을 만들어 보냅니다. 그래서 수정 코드에는 db.add도 UPDATE 문도 없습니다.

초보자가 자주 하는 실수

edit.html의 action
증상: 수정을 저장했는데 기존 기록은 그대로이고 같은 내용의 새 기록이 하나 더 생깁니다.
원인: edit.html을 form.html에서 복사하고 action="/books"를 그대로 두면 등록 함수 book_create로 갑니다.
고치는 법: action="/books/{{ book_id }}"로 고칩니다.

댓글

아직 댓글이 없습니다.