■ FastAPI 클래스를 사용해 SQLITE 데이터베이스에서 단순 CRUD 애플리케이션을 만드는 방법을 보여준다.
▶ database/connection.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
from sqlmodel import SQLModel, Session, create_engine databaseFile = "test.db" databaseConnectionString = f"sqlite:///{databaseFile}" connectionArgumentDictionary = {"check_same_thread" : False} engineURL = create_engine(databaseConnectionString, echo = True, connect_args = connectionArgumentDictionary) def connect(): SQLModel.metadata.create_all(engineURL) def getSession(): with Session(engineURL) as session: yield session |
▶ model/event.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
from sqlmodel import JSON, SQLModel, Field, Column from typing import List class Event(SQLModel, table = True): id : int = Field(default = None, primary_key = True) title : str image : str description : str tagList : List[str] = Field(sa_column = Column(JSON)) location : str class EventUpdate(SQLModel): title : str | None image : str | None description : str | None tagList : List[str] | None location : str | None |
▶ 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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
from fastapi import APIRouter, Depends, HTTPException, Request, status from sqlmodel import select from typing import List from database.connection import getSession from model.event import Event, EventUpdate eventList = [] eventAPIRouter = APIRouter(tags = ["Event"]) @eventAPIRouter.post("/new") async def createEvent(newEvent : Event, session = Depends(getSession)) -> dict: session.add(newEvent) session.commit() session.refresh(newEvent) return {"message" : "Event created successfully"} @eventAPIRouter.get("/", response_model = List[Event]) async def getAllEventList(session = Depends(getSession)) -> List[Event]: statement = select(Event) eventList = session.exec(statement).all() return eventList @eventAPIRouter.get("/{id}", response_model = Event) async def getEvent(id : int, session = Depends(getSession)) -> Event: event = session.get(Event, id) if event: return event raise HTTPException(status_code = status.HTTP_404_NOT_FOUND, detail = "Event with supplied ID does not exist") @eventAPIRouter.put("/edit/{id}", response_model = Event) async def updateEvent(id : int, eventUpdate : EventUpdate, session = Depends(getSession)) -> Event: event = session.get(Event, id) if event: event_data = eventUpdate.dict(exclude_unset = True) for key, value in event_data.items(): setattr(event, key, value) session.add(event) session.commit() session.refresh(event) return event raise HTTPException(status_code = status.HTTP_404_NOT_FOUND, detail = "Event with supplied ID does not exist") @eventAPIRouter.delete("/{id}") async def deleteEvent(id : int, session = Depends(getSession)) -> dict: event = session.get(Event, id) if event: session.delete(event) session.commit() return {"message" : "Event deleted successfully"} raise HTTPException(status_code = status.HTTP_404_NOT_FOUND, detail = "Event with supplied ID does not exist") |
▶ main.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 |
from fastapi import FastAPI from fastapi.responses import RedirectResponse from typing import List import uvicorn from database.connection import connect from route.event import eventAPIRouter fastAPI = FastAPI() fastAPI.include_router(eventAPIRouter, prefix = "/event") @fastAPI.on_event("startup") def onStarting(): connect() @fastAPI.get("/") async def home(): return RedirectResponse(url = "/event/") if __name__ == '__main__': uvicorn.run("main:fastAPI", host = "0.0.0.0", port = 8000, reload = True) |
▶ 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 39 40 41 |
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 greenlet==3.0.3 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 SQLAlchemy==2.0.30 sqlmodel==0.0.18 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 |