■ FastAPI 애플리케이션을 구조화하는 방법을 보여준다.
▶ 디렉토리 및 파일 구조
1 2 3 4 5 6 7 8 9 10 11 12 |
planner/ model/ __init__.py event.py user.py route/ __init__.ps event.py user.py main.py |
▶ model/__init__.py
1 2 3 |
▶ model/event.py
1 2 3 4 5 6 7 8 9 10 11 12 |
from typing import List from pydantic import BaseModel class Event(BaseModel): id : int title : str image : str description : str tagList : List[str] location : str |
▶ model/user.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
from pydantic import BaseModel, EmailStr from typing import Optional, List from model.event import Event class User(BaseModel): email : EmailStr password : str eventList : Optional[List[Event]] class UserSignIn(BaseModel): email : EmailStr password : str |
▶ route/__init__.py
1 2 3 |
▶ route/event.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
from fastapi import APIRouter, Body, HTTPException, status from typing import List from model.event import Event eventList = [] eventAPIRouter = APIRouter(tags = ["Event"]) @eventAPIRouter.get("/", response_model = List[Event]) async def getAllEventList() -> List[Event]: return eventList @eventAPIRouter.get("/{id}", response_model = Event) async def getEvent(id : int) -> Event: for event in eventList: if event.id == id: return event raise HTTPException(status_code = status.HTTP_404_NOT_FOUND, detail = "Event with supplied ID does not exist") @eventAPIRouter.post("/new") async def createEvent(body : Event = Body(...)) -> dict: eventList.append(body) return {"message" : "Event created successfully"} @eventAPIRouter.delete("/{id}") async def deleteEvent(id : int) -> dict: for event in eventList: if event.id == id: eventList.remove(event) return {"message" : "Event deleted successfully"} raise HTTPException(status_code = status.HTTP_404_NOT_FOUND, detail = "Event with supplied ID does not exist") @eventAPIRouter.delete("/") async def deleteAllEvents() -> dict: events.clear() return {"message" : "Events deleted successfully"} |
▶ route/user.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
from fastapi import APIRouter, HTTPException, status from model.user import User, UserSignIn userDictionary = {} userAPIRouter = APIRouter(tags = ["User"]) @userAPIRouter.post("/signup") async def addNewUser(user : User) -> dict: if user.email in userDictionary: raise HTTPException(status_code = status.HTTP_409_CONFLICT, detail = "User with supplied username exists") userDictionary[user.email] = user return {"message" : "User successfully registered!"} @userAPIRouter.post("/signin") async def loginUser(userSignIn : UserSignIn) -> dict: if userSignIn.email not in userDictionary: raise HTTPException(status_code = status.HTTP_404_NOT_FOUND, detail = "User does not exist") if userDictionary[userSignIn.email].password != userSignIn.password: raise HTTPException(status_code = status.HTTP_403_FORBIDDEN, detail = "Wrong credential passed") return {"message" : "User signed in successfully"} |
▶ main/user.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
from fastapi import FastAPI from fastapi.responses import RedirectResponse from route.user import userAPIRouter from route.event import eventAPIRouter fastAPI = FastAPI() fastAPI.include_router(userAPIRouter , prefix = "/user" ) fastAPI.include_router(eventAPIRouter, prefix = "/event") @fastAPI.get("/") async def home(): return RedirectResponse(url = "/event/") |
▶ requirements.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
annotated-types==0.7.0 anyio==4.3.0 certifi==2024.2.2 click==8.1.7 dnspython==2.6.1 email_validator==2.1.1 exceptiongroup==1.2.1 fastapi==0.111.0 fastapi-cli==0.0.4 h11==0.14.0 httpcore==1.0.5 httptools==0.6.1 httpx==0.27.0 idna==3.7 Jinja2==3.1.4 markdown-it-py==3.0.0 MarkupSafe==2.1.5 mdurl==0.1.2 orjson==3.10.3 pydantic==2.7.1 pydantic_core==2.18.2 Pygments==2.18.0 python-dotenv==1.0.1 python-multipart==0.0.9 PyYAML==6.0.1 rich==13.7.1 shellingham==1.5.4 sniffio==1.3.1 starlette==0.37.2 typer==0.12.3 typing_extensions==4.11.0 ujson==5.10.0 uvicorn==0.29.0 uvloop==0.19.0 watchfiles==0.21.0 websockets==12.0 |