์๊ธฐ๋ฅ #48
์งํ์ค์๊ธฐ๋ฅ #44: ๐ Mangement Cloud server FastAPI ํ๋ก์ ํธ
๐ฅ Epic 1 - Task 3 ๐ FastAPI ๊ธฐ๋ณธ ์๋ฒ ๊ตฌ์ถ
0%
์ค๋ช
๐ฅ Epic 1 โ Task 3¶
๐ FastAPI ๊ธฐ๋ณธ ์๋ฒ ๊ตฌ์ถ¶
๐ ์์ ๊ฐ์¶
- FastAPI ๊ธฐ๋ฐ mgmt ์๋ฒ์ ์ฒซ ์คํ ํ๊ฒฝ์ ๊ตฌ์ถํ๋ ๋จ๊ณ์ด๋ค.
- ํ๋ก์ ํธ๊ฐ ์ ์์ ์ผ๋ก ๋์ํ๋์ง ํ์ธํ๊ธฐ ์ํด ํต์ฌ ์ํธ๋ฆฌํฌ์ธํธ(main.py)๋ฅผ ์์ฑํ๊ณ ,
- ๊ธฐ๋ณธ์ ์ธ API ์๋ํฌ์ธํธ(/ping)๋ฅผ ๊ตฌํํ์ฌ ์๋ฒ๊ฐ ์ ์์ ์ผ๋ก ์๋ตํ๋์ง ๊ฒ์ฆํ๋ค.
์ด ์์ ์ ์ดํ ๋ชจ๋ ๊ธฐ๋ฅ ๊ฐ๋ฐ์ ๊ธฐ๋ฐ์ด ๋๋ ์ต์ด ์คํ ํ๊ฒฝ ๊ตฌ์ฑ ๋จ๊ณ์ด๋ค.
๐ฏ ์์ ๋ชฉ์ ¶
-
FastAPI ์๋ฒ๊ฐ ์ ์์ ์ผ๋ก ์คํ๋๋์ง ํ์ธํ๋ค.
-
uvicorn์ ํตํด ๊ฐ๋ฐ ํ๊ฒฝ์์ ์๋ฒ๋ฅผ ๊ตฌ๋ํ ์ ์๋๋ก ํ๋ค.
-
/ping API๋ฅผ ๊ตฌํํ์ฌ ๊ธฐ๋ณธ์ ์ธ ์์ฒญ/์๋ต ํ๋ฆ์ ๊ฒ์ฆํ๋ค.
-
PyCharm ๋๋ฒ๊ทธ ํ๊ฒฝ๊ณผ test_main.http ํ์ผ์ ํ์ฉํด API ํ ์คํธ ๊ธฐ๋ฐ์ ๋ง๋ จํ๋ค.
๐ ๏ธ ์งํ ๋ด์ฉ¶
๐๏ธ 1. FastAPI ์ํธ๋ฆฌํฌ์ธํธ(main.py) ์์ฑ¶
FastAPI ์๋ฒ์ ์์์ ์ด ๋๋ main.py ํ์ผ์ ์์ฑํ๊ณ ,
FastAPI ์ธ์คํด์ค๋ฅผ ์ด๊ธฐํํ๋ค.
from fastapi import FastAPI
app = FastAPI()
@app.get("/ping")
def ping():
return {"msg": "pong"}
if __name__ == "__main__":
import uvicorn
uvicorn.run("app.main:app", host="127.0.0.1", port=8000, reload=True)
-
reload=True๋ ๊ฐ๋ฐ ํธ์์ฑ ํฅ์
-
๋๋ฒ๊น ์์๋ reload=False๋ก ๋ณ๊ฒฝ ๊ฐ๋ฅ
๐๏ธ 2. uvicorn ์คํ ํ ์คํธ¶
-
PyCharm์์ Run/Debug Configuration์ ์์ฑํ์ฌ FastAPI ์๋ฒ๊ฐ ์ ์์ ์ผ๋ก ์คํ๋๋์ง ํ์ธํ๋ค.
-
์คํ ํ ๋ธ๋ผ์ฐ์ ์์
๐ http://127.0.0.1:8000/ping
์๋ต์ด { "msg": "pong" } ์ด๋ฉด ์ ์
๐๏ธ 3. test_main.http ํ์ผ์ ํ์ฉํ API ํ ์คํธ¶
- PyCharm์ด ์๋ ์์ฑํ .http ํ์ผ์ ํ์ฉํ์ฌ FastAPI ์๋ํฌ์ธํธ๋ฅผ ์ง์ ํธ์ถํด๋ณธ๋ค.
์์:
### Ping Test
GET http://127.0.0.1:8000/ping
Accept: application/json
-
Send Request ๋ฒํผ ํด๋ฆญ
-
์๋ต์ด ์ ์์ ์ผ๋ก ํ์๋๋์ง ํ์ธ
๐๏ธ 4. ๋ผ์ฐํฐ ๊ตฌ์กฐ ๋ถ๋ฆฌ ์ค๋น¶
ํฅํ /server, /control, /ssh ๋ฑ ๊ธฐ๋ฅ๋ณ ๋ผ์ฐํฐ๋ฅผ ๋ถ๋ฆฌํ๊ธฐ ์ํด
app/routers/health.py ํ์ผ์ ์์ฑํ๊ณ /ping API๋ฅผ ์ด๋ํ ์ค๋น๋ฅผ ํ๋ค.
์์:
from fastapi import APIRouter
router = APIRouter()
@router.get("/ping")
def ping():
return {"msg": "pong"}
๊ทธ๋ฆฌ๊ณ main.py์์ ๋ผ์ฐํฐ๋ฅผ ๋ฑ๋กํ๋ค:
from fastapi import FastAPI
from app.routers import health
app = FastAPI()
app.include_router(health.router)
๐๏ธ 5. FastAPI ์๋ ๋ฌธ์ ํ์ธ¶
-
FastAPI๋ ๊ธฐ๋ณธ์ ์ผ๋ก ์๋ ๋ฌธ์๋ฅผ ์ ๊ณตํ๋ค.
-
Swagger UI
๐ http://127.0.0.1:8000/docs -
ReDoc
๐ http://127.0.0.1:8000/redoc
์ฌ๊ธฐ์ /ping API๊ฐ ์ ์์ ์ผ๋ก ํ์๋๋์ง ํ์ธํ๋ค.
๐ ์ฐ์ถ๋ฌผ¶
-
FastAPI ์ํธ๋ฆฌํฌ์ธํธ(main.py)
-
/pingAPI ๊ตฌํ -
uvicorn ์คํ ๋ฐ ๋๋ฒ๊ทธ ํ๊ฒฝ ๊ตฌ์ฑ
-
test_main.http ํ ์คํธ ์๋ฃ
-
๋ผ์ฐํฐ ๊ตฌ์กฐ ๋ถ๋ฆฌ ์ค๋น ์๋ฃ
-
Swagger/ReDoc ์๋ ๋ฌธ์ ์ ์ ํ์
ํ์ํ ๋ฐ์ดํฐ๊ฐ ์์ต๋๋ค.