
๐ฐ FastAPI ๊ณต์๋ฌธ์๋ฅผ ๋ณด๋ฉด์ ๊ฐ์ธ์ ์ผ๋ก ์ ๋ฆฌํ ๊ธ ์
๋๋ค.
html์ jinja2 Template์ ์ฌ์ฉํ ์ ์๋ค. context๋ฅผ ์ฌ์ฉํ์ฌ ํธํ๊ฒ ํ์ด์ง๋ฅผ ๊พธ๋ฐ ์ ์๋ค.
pip install jinja2
templates ํด๋์ static ํด๋๋ฅผ ๋ง๋ ๋ค.
templates ํด๋์๋ html ํ์ผ์ static ํด๋์๋ ์ ์ ํ์ผ์ ๋ฃ๋๋ค.

<html>
<head>
<title>Item Details</title>
<link href="{{ url_for('static', path='css/index.css') }}" rel="stylesheet">
</head>
<body>
<h1>Item ID: {{ id }}</h1>
</body>
</html>
StaticFiles๋ฅผ ์ฌ์ฉํ์ฌ ์ ์ ํ์ผ(css, js, img, ...)์ ๊ด๋ฆฌํ ์ ์๋ค.
StaticFiles๋ฅผ importํ๊ณ app์ ํน์ ๊ฒฝ๋ก์ StaticFiles() ์ธ์คํด์ค๋ฅผ Mountํ๋ค.
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")

index.css
h1 {
color: green;
}
์ด์ main.py๋ฅผ ์์ฑํ๋ค.
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
@app.get("/items/{id}", response_class=HTMLResponse)
async def read_item(request: Request, id: str):
return templates.TemplateResponse(
request=request, name="index.html", context={"id": id}
)
๋ฐํ์ template ๊ฐ์ฒด๋ฅผ ๋ฐํํ๋ฉด html ํ์ผ, context, request์ ํจ๊ป ๋ฐํํ๋ค.
context ๊ฐ์ ์ฌ์ฉํด html์์ for, if, ๋ณ์ ๋ฑ์ ์ฌ์ฉํ ์ ์๋ค.

'Back-end & Server > FastAPI' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[FastAPI] ๋ฐฐํฌ (0) | 2024.02.24 |
---|---|
[FastAPI] Metadata Docs, Testing, Debugging (0) | 2024.02.24 |
[FastAPI] Background Task (0) | 2024.02.23 |
[FastAPI] ํ์ผ ๋ถํ (0) | 2024.02.23 |
[FastAPI] Relational Database (0) | 2024.02.22 |