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
게시판

05 / 14

HTML 파일로 분리

HTML을 파이썬 문자열 안에 계속 넣으면 금방 지저분해져요. HTML은 HTML 파일에 쓰고, 파이썬은 그 파일을 보내 주기만 하게 바꿔요.

편집기에 templates/index.html 탭이 생겼어요. 비어 있으니 채워요.

templates/index.html
<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>crack.log</title>
</head>
<body>
  <header>
    <a href="/">crack.log</a>
  </header>
  <main>
    <h1>내 블로그</h1>
    <p>FastAPI로 만드는 velog 닮은 블로그</p>
  </main>
</body>
</html>
  • <head> 화면에 안 보이는 설정. <title>은 브라우저 탭 이름이에요.
  • <body> 화면에 보이는 전부.
  • <header>, <main> 영역을 나누는 태그예요. 지금은 아무 효과도 없지만 CSS 입힐 때 써요.
  • <a href="/"> 링크예요. 누르면 href 주소로 가요.

이제 app.py가 이 파일을 보내게 바꿔요. 전체를 이걸로 교체하세요.

app.py
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates

app = FastAPI()
templates = Jinja2Templates(directory="templates")


@app.get("/", response_class=HTMLResponse)
def home(request: Request):
    return templates.TemplateResponse(request, "index.html")
  • Jinja2Templates(directory="templates") templates 폴더에서 파일을 찾겠다는 뜻이에요.
  • templates.TemplateResponse(request, "index.html") 그 폴더의 index.html을 보내요. request는 "누가 요청했는지" 정보인데 Jinja2가 필요로 해서 같이 넘겨요.

실행하면 오른쪽이 바뀌어요. 아직 못생긴 게 정상이에요. 7단계에서 옷을 입혀요.

이 단계 전체 코드
app.py
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates

app = FastAPI()
templates = Jinja2Templates(directory="templates")


@app.get("/", response_class=HTMLResponse)
def home(request: Request):
    return templates.TemplateResponse(request, "index.html")
templates/index.html
<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>crack.log</title>
</head>
<body>
  <header>
    <a href="/">crack.log</a>
  </header>
  <main>
    <h1>내 블로그</h1>
    <p>FastAPI로 만드는 velog 닮은 블로그</p>
  </main>
</body>
</html>
준비
localhost:8000 ↗