1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
게시판

12 / 14

글쓰기 POST

지금까지는 전부 GET이었어요. 이제 폼으로 새 글을 보내는 POST를 해요. 필요한 건 셋. 글쓰기 화면(GET /write), 받는 주소(POST /posts), 헤더의 버튼.

templates/base.html의 헤더에 링크를 넣어요. 버튼과 링크를 <span>으로 묶어서 오른쪽에 나란히 놓아요.

templates/base.html
  <header>
    <a href="/">crack.log</a>
    <span>
      <button id="theme">☾</button>
      <a class="write" href="/write">새 글 작성</a>
    </span>
  </header>

templates/write.html을 채워요.

templates/write.html
{% extends "base.html" %}
{% block content %}
<form class="editor" action="/posts" method="post">
  <input name="title" placeholder="제목" required>
  <input name="author" placeholder="닉네임" required>
  <input name="summary" placeholder="한 줄 요약" required>
  <textarea name="body" placeholder="본문" rows="12" required></textarea>
  <button type="submit">출간하기</button>
</form>
{% endblock %}
  • <form action="/posts" method="post"> 버튼을 누르면 안의 값들을 /posts로 POST 보내요.
  • <input name="title"> 한 줄 입력칸. name이 서버에서 받을 이름이에요.
  • <textarea> 여러 줄 입력칸.
  • required 비우면 못 보내게.

app.py 맨 위 import를 바꾸고, 맨 아래에 주소 두 개를 추가해요.

app.py
from datetime import date

from fastapi import FastAPI, Form, HTTPException, Request
from fastapi.responses import HTMLResponse, RedirectResponse
app.py
@app.get("/write", response_class=HTMLResponse)
def write_form(request: Request):
    return templates.TemplateResponse(request, "write.html")


@app.post("/posts")
def create_post(
    title: str = Form(),
    author: str = Form(),
    summary: str = Form(),
    body: str = Form(),
):
    new_id = max((post["id"] for post in posts), default=0) + 1
    posts.append({
        "id": new_id,
        "title": title,
        "summary": summary,
        "body": body,
        "date": date.today().strftime("%Y년 %m월 %d일"),
        "author": author,
        "likes": 0,
        "image": f"thumb{new_id % 4 + 1}.svg",
    })
    return RedirectResponse(f"/posts/{new_id}", status_code=303)
  • @app.post("/posts") 같은 주소라도 메서드가 다르면 다른 함수예요.
  • title: str = Form() 폼에서 name="title"로 온 값을 받아요.
  • 새 id는 제일 큰 id에 1 더한 값. 리스트에 딕셔너리를 붙여요.
  • RedirectResponse(..., status_code=303) "됐어, 이 주소로 가". 브라우저가 방금 만든 글 상세로 이동해요.

static/style.css 맨 아래에 버튼과 폼 모양을 추가해요.

static/style.css
.write {
  margin-left: 12px;
  padding: 6px 16px;
  border: 1px solid var(--text);
  border-radius: 16px;
  font-size: 14px;
  font-weight: 700;
  color: var(--text);
  text-decoration: none;
}

.editor { max-width: 720px; margin: 0 auto; display: grid; gap: 12px; }
.editor input, .editor textarea {
  padding: 12px;
  font: inherit;
  background: var(--panel);
  color: var(--text);
  border: 1px solid var(--line);
  border-radius: 4px;
}
.editor button {
  padding: 10px;
  font: inherit;
  font-weight: 700;
  color: #fff;
  background: var(--mint);
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

실행해서 글을 하나 써 보세요. 출간하면 상세 페이지로 가고, 로고를 누르면 목록에 카드가 하나 늘어 있어요.

이 단계 전체 코드
app.py
from datetime import date

from fastapi import FastAPI, Form, HTTPException, Request
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates

app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")

posts = [
    {
        "id": 1,
        "title": "FastAPI 첫 서버 띄우기",
        "summary": "uvicorn 한 줄이면 끝. 흰 화면에 Hello World가 뜨는 순간부터 시작.",
        "body": "터미널에 uvicorn app:app --reload 를 치면 서버가 뜬다. 브라우저에서 localhost:8000 을 열면 내가 return 한 글자가 그대로 보인다. 여기서부터 전부 시작이다.",
        "date": "2026년 10월 10일",
        "author": "sfadfe",
        "likes": 518,
        "image": "thumb1.svg",
    },
    {
        "id": 2,
        "title": "Jinja2로 HTML 분리하기",
        "summary": "app.py 안에 HTML을 문자열로 두면 금방 지저분해진다. templates 폴더로 꺼내자.",
        "body": "Jinja2Templates(directory='templates') 한 줄이면 HTML 파일을 따로 둘 수 있다. 중괄호 두 개 안에 파이썬 값을 넣으면 그 자리에 찍힌다. 파일이 나뉘니까 어디를 고칠지 바로 보인다.",
        "date": "2026년 10월 11일",
        "author": "aa_100",
        "likes": 523,
        "image": "thumb2.svg",
    },
    {
        "id": 3,
        "title": "fetch로 DELETE 보내기",
        "summary": "버튼 하나에 fetch 한 줄. 서버는 리스트에서 글을 빼고 200을 돌려준다.",
        "body": "주소창으로는 GET밖에 못 보낸다. DELETE 는 JS 의 fetch 로 보낸다. 서버 쪽은 @app.delete 로 받는다. 받으면 리스트에서 글을 빼고 ok 를 돌려준다.",
        "date": "2026년 10월 12일",
        "author": "nosmeri",
        "likes": 9,
        "image": "thumb3.svg",
    },
]


@app.get("/", response_class=HTMLResponse)
def home(request: Request):
    return templates.TemplateResponse(request, "index.html", {"posts": posts})


@app.get("/posts/{post_id}", response_class=HTMLResponse)
def post_detail(request: Request, post_id: int):
    for post in posts:
        if post["id"] == post_id:
            return templates.TemplateResponse(request, "post.html", {"post": post})
    raise HTTPException(status_code=404, detail="그런 글은 없어요")


@app.get("/write", response_class=HTMLResponse)
def write_form(request: Request):
    return templates.TemplateResponse(request, "write.html")


@app.post("/posts")
def create_post(
    title: str = Form(),
    author: str = Form(),
    summary: str = Form(),
    body: str = Form(),
):
    new_id = max((post["id"] for post in posts), default=0) + 1
    posts.append({
        "id": new_id,
        "title": title,
        "summary": summary,
        "body": body,
        "date": date.today().strftime("%Y년 %m월 %d일"),
        "author": author,
        "likes": 0,
        "image": f"thumb{new_id % 4 + 1}.svg",
    })
    return RedirectResponse(f"/posts/{new_id}", status_code=303)
templates/base.html
<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>crack.log</title>
  <link rel="stylesheet" href="/static/style.css">
</head>
<body>
  <header>
    <a href="/">crack.log</a>
    <span>
      <button id="theme">☾</button>
      <a class="write" href="/write">새 글 작성</a>
    </span>
  </header>
  <main>
    {% block content %}{% endblock %}
  </main>
  <script src="/static/script.js"></script>
</body>
</html>
templates/index.html
{% extends "base.html" %}
{% block content %}
<h1>내 블로그</h1>
<div class="cards">
  {% for post in posts %}
  <article class="card">
    <a href="/posts/{{ post.id }}">
      <img class="thumb" src="/static/{{ post.image }}" alt="">
      <div class="body">
        <h2>{{ post.title }}</h2>
        <p>{{ post.summary }}</p>
        <span class="date">{{ post.date }}</span>
      </div>
    </a>
    <div class="foot">
      <span>by <b>{{ post.author }}</b></span>
      <span>♥ {{ post.likes }}</span>
    </div>
  </article>
  {% endfor %}
</div>
{% endblock %}
templates/post.html
{% extends "base.html" %}
{% block content %}
<article class="post">
  <h1>{{ post.title }}</h1>
  <p class="meta">{{ post.author }}, {{ post.date }}</p>
  <img class="cover" src="/static/{{ post.image }}" alt="">
  <p class="content">{{ post.body }}</p>
  <a class="back" href="/">목록으로</a>
</article>
{% endblock %}
templates/write.html
{% extends "base.html" %}
{% block content %}
<form class="editor" action="/posts" method="post">
  <input name="title" placeholder="제목" required>
  <input name="author" placeholder="닉네임" required>
  <input name="summary" placeholder="한 줄 요약" required>
  <textarea name="body" placeholder="본문" rows="12" required></textarea>
  <button type="submit">출간하기</button>
</form>
{% endblock %}
static/style.css
:root {
  --bg: #f8f9fa;
  --panel: #ffffff;
  --text: #212529;
  --muted: #868e96;
  --line: #e9ecef;
  --mint: #12b886;
}

* { box-sizing: border-box; }

body {
  margin: 0;
  font-family: -apple-system, "Segoe UI", "Noto Sans KR", "Malgun Gothic", sans-serif;
  background: var(--bg);
  color: var(--text);
}

header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 32px;
  background: var(--panel);
  border-bottom: 1px solid var(--line);
}

header a {
  font-size: 22px;
  font-weight: 800;
  color: var(--mint);
  text-decoration: none;
}

main {
  max-width: 1000px;
  margin: 0 auto;
  padding: 32px;
}

h1 { font-size: 22px; }

.card {
  background: var(--panel);
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
}

.card a { color: inherit; text-decoration: none; }
.card .thumb { display: block; width: 100%; height: 160px; object-fit: cover; }
.card .body { padding: 16px; }
.card h2 { margin: 0 0 8px; font-size: 16px; }
.card p { margin: 0 0 12px; font-size: 14px; line-height: 1.5; color: var(--muted); }
.card .date { font-size: 12px; color: var(--muted); }

.card .foot {
  display: flex;
  justify-content: space-between;
  padding: 10px 16px;
  border-top: 1px solid var(--line);
  font-size: 12px;
  color: var(--muted);
}

.cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 24px;
}

.card {
  transition: transform 0.25s, box-shadow 0.25s;
}

.card:hover {
  transform: translateY(-8px);
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.12);
}

.dark {
  --bg: #121212;
  --panel: #1e1e1e;
  --text: #ececec;
  --muted: #a0a0a0;
  --line: #2a2a2a;
}

#theme {
  font-size: 20px;
  background: none;
  border: none;
  color: var(--text);
  cursor: pointer;
}

.post { max-width: 720px; margin: 0 auto; }
.post h1 { font-size: 36px; margin-bottom: 8px; }
.post .meta { color: var(--muted); margin-bottom: 24px; }
.post .cover { width: 100%; border-radius: 8px; }
.post .content { font-size: 17px; line-height: 1.8; }
.post .back { color: var(--mint); text-decoration: none; }

.write {
  margin-left: 12px;
  padding: 6px 16px;
  border: 1px solid var(--text);
  border-radius: 16px;
  font-size: 14px;
  font-weight: 700;
  color: var(--text);
  text-decoration: none;
}

.editor { max-width: 720px; margin: 0 auto; display: grid; gap: 12px; }
.editor input, .editor textarea {
  padding: 12px;
  font: inherit;
  background: var(--panel);
  color: var(--text);
  border: 1px solid var(--line);
  border-radius: 4px;
}
.editor button {
  padding: 10px;
  font: inherit;
  font-weight: 700;
  color: #fff;
  background: var(--mint);
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
static/script.js
const button = document.getElementById("theme");

function apply(dark) {
  document.body.classList.toggle("dark", dark);
  button.textContent = dark ? "☀" : "☾";
}

apply(localStorage.getItem("theme") === "dark");

button.addEventListener("click", () => {
  const dark = !document.body.classList.contains("dark");
  localStorage.setItem("theme", dark ? "dark" : "light");
  apply(dark);
});
준비
localhost:8000 ↗