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

코드 작성과 설명

· 3 views

[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>{{ book.title }}</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

        <a class="button" href="/books/new">등록</a>
등록 화면 주소 /books/new로 가는 링크입니다. style.css의 button 모양으로 보입니다.


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

name="title"은 main.py의 매개변수 title과 이름이 같아야 합니다.

▼ Code

Path: templates/form.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" 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="/">목록</a>
        </div>
    </form>
</div>
</body>
</html>

▼ Explain

Path: templates/form.html

    {% if error %}
오류 문구가 있을 때만 빨간 글자로 보여 줍니다.

    <form action="/books" method="post">
저장을 누르면 POST /books로 입력값을 보냅니다.

            <input id="title" type="text" name="title" value="{{ title }}" maxlength="200">
name="title"이 폼 값의 이름입니다. value는 오류가 났을 때 입력한 글자를 되살립니다. maxlength는 테이블 길이와 맞춥니다.

            <textarea id="memo" name="memo" rows="5" maxlength="1000">{{ memo }}</textarea>
여러 줄 입력칸입니다. textarea는 value 대신 태그 사이에 값을 넣습니다.


개념 정리: 폼 전송과 Form

form 태그의 method="post"와 action="/books"는 저장 버튼을 누를 때 POST /books 요청을 보내게 합니다. 입력칸의 name이 값의 이름입니다. FastAPI 함수에서 title: str = Form("")이라고 적으면 같은 이름의 폼 값을 title에 넣어 줍니다. 값이 오지 않으면 괄호 안의 기본값 ""이 들어갑니다. 폼 값을 읽는 일은 python-multipart 라이브러리가 맡습니다.

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

맨 위 import에 Form과 RedirectResponse를 더합니다.
templates 줄 아래에 check_input을, 목록 함수 아래에 book_new와 book_create를 더합니다. 기존 book_list는 그대로 둡니다.

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


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

▼ Explain

Path: main.py

from fastapi import Depends, FastAPI, Form, Request
폼 값을 받는 Form을 더 가져옵니다.

from fastapi.responses import RedirectResponse
다른 주소로 가라는 응답을 만듭니다.

def check_input(title, author, memo):
입력 검사를 한곳에 모은 함수입니다. 문제가 있으면 오류 문구를, 없으면 빈 문자열을 돌려줍니다. 수정 장에서도 씁니다.

    if len(title) > 200 or len(author) > 100 or len(memo) > 1000:
테이블 길이보다 긴 값은 저장하지 않습니다. 입력칸의 maxlength는 브라우저만 막으므로 서버에서도 검사합니다.

@app.get("/books/new")
빈 등록 화면을 보여 주는 주소입니다.

    data = {"title": "", "author": "", "memo": "", "error": ""}
처음 열 때는 입력칸과 오류 문구를 빈 값으로 넘깁니다.

@app.post("/books")
폼이 보낸 POST /books를 받아 저장합니다.

    title: str = Form(""),
폼의 name="title" 값을 받습니다.

    title = title.strip()
앞뒤 공백을 지웁니다. 공백만 넣은 제목을 빈 제목으로 보기 위해서입니다.

    if error:
검사에 걸리면 저장하지 않고 입력값과 오류 문구를 담아 같은 폼을 다시 보여 줍니다.

    db.add(Book(title=title, author=author, memo=memo))
새 Book 객체를 세션에 올립니다. 아직 데이터베이스에 저장되지는 않았습니다.

    db.commit()
INSERT를 실행하고 확정합니다. 이 줄이 없으면 저장되지 않습니다.

    return RedirectResponse("/", status_code=303)
303과 함께 / 로 다시 가라고 알립니다.


개념 정리: 리다이렉트와 PRG 패턴

저장에 성공하면 화면 대신 RedirectResponse("/", status_code=303)을 돌려줍니다. 브라우저는 303을 받으면 Location에 적힌 / 를 GET으로 새로 요청합니다. POST 다음에 Redirect, 그다음 GET으로 이어지는 이 흐름을 PRG(Post/Redirect/Get) 패턴이라고 부릅니다. 브라우저의 마지막 요청이 GET이 되므로 새로고침해도 저장 요청이 다시 나가지 않습니다.

image

실무에서는: 입력 검증 도구

이 책은 검증을 if 문으로 직접 씁니다. 실무에서는 Pydantic 모델에 길이와 필수 규칙을 선언해 검증을 맡기는 방식도 많이 씁니다. 규칙이 늘어나도 함수가 길어지지 않고 오류 문구를 한곳에서 관리할 수 있습니다.

초보자가 자주 하는 실수

status_code=303을 빠뜨림
증상: 저장 버튼을 누르면 {"detail":"Method Not Allowed"}가 보입니다.
원인: RedirectResponse의 기본값은 307입니다. 307은 같은 메서드로 다시 요청하라는 뜻이어서 브라우저가 POST / 를 보내고 / 에는 POST 함수가 없어 405가 됩니다.
고치는 법: RedirectResponse("/", status_code=303)으로 적습니다.

db.commit()을 빠뜨림
증상: 목록으로 돌아오지만 새 기록이 없습니다. 오류도 나지 않습니다.
원인: add는 세션에 올리기만 하고 commit이 있어야 INSERT가 확정됩니다. 요청이 끝나면 세션이 닫히며 확정되지 않은 작업은 사라집니다.
고치는 법: db.add 다음 줄에 db.commit()을 넣습니다.

댓글

아직 댓글이 없습니다.