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>
    <form class="search" action="/" method="get">
        <input type="text" name="keyword" value="{{ keyword }}" placeholder="책 제목">
        <button type="submit">검색</button>
    </form>
    <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>
    {% elif keyword %}
    <p class="empty">검색 결과가 없습니다.</p>
    {% else %}
    <p class="empty">기록이 없습니다.</p>
    {% endif %}
</div>
</body>
</html>

▼ Explain

Path: templates/list.html

    <form class="search" action="/" method="get">
GET 폼은 입력값을 주소 뒤에 ?keyword=값 으로 붙여 보냅니다.

        <input type="text" name="keyword" value="{{ keyword }}" placeholder="책 제목">
name="keyword"가 함수의 매개변수 이름과 같아야 합니다. value는 검색한 뒤에도 검색어를 남겨 둡니다.

    {% elif keyword %}
기록은 없는데 검색어가 있으면 검색 결과가 없다는 뜻입니다.


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

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


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, keyword: str = "", db: Session = Depends(get_db)):
    keyword = keyword.strip()
    query = select(Book).order_by(Book.id.desc())
    if keyword:
        query = query.where(Book.title.contains(keyword))
    books = db.scalars(query).all()
    return templates.TemplateResponse(request, "list.html", {"books": books, "keyword": keyword})


@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

def book_list(request: Request, keyword: str = "", db: Session = Depends(get_db)):
주소에 없는 이름을 매개변수로 적으면 쿼리 매개변수가 됩니다. 기본값 ""이 있어 ?keyword= 가 없어도 됩니다.

    keyword = keyword.strip()
검색어 앞뒤 공백을 지웁니다.

    query = select(Book).order_by(Book.id.desc())
기본 조회문을 먼저 만듭니다.

    if keyword:
검색어가 있을 때만 조건을 더합니다. 빈 검색어면 전체 목록입니다.

        query = query.where(Book.title.contains(keyword))
제목에 검색어가 들어 있는 행만 고릅니다. SQL로는 title LIKE '%검색어%'가 됩니다.

    return templates.TemplateResponse(request, "list.html", {"books": books, "keyword": keyword})
검색어도 템플릿에 넘겨 검색칸에 다시 보여 줍니다.


개념 정리: 쿼리 매개변수

주소의 ? 뒤에 이름=값 으로 붙는 부분을 쿼리 문자열이라고 합니다. FastAPI 함수의 매개변수 중 경로에 없는 이름은 쿼리 매개변수로 읽습니다. 한글 검색어는 주소에 넣을 때 %EC%99%95 처럼 바뀌어 보내지고 FastAPI가 원래 글자로 되돌려 넣어 줍니다.

버전이 다를 때: 대소문자와 검색

contains는 LIKE로 바뀌고 MySQL의 utf8mb4_unicode_ci 정렬 규칙은 영문 대소문자를 구분하지 않습니다. 그래서 영어 제목은 "harry"로 찾아도 "Harry"가 나옵니다. 다른 데이터베이스나 다른 정렬 규칙에서는 결과가 다를 수 있습니다.

댓글

아직 댓글이 없습니다.