이제 이어서 database.py와 schemas.py에 대해서 알아보자
앞서서 본 코드는 다음과 같았다.
router = APIRouter(
prefix="/patients",
tags=["patients"],
responses={404: {"description": "Not found"}}
)
@router.post("/", response_model=schemas.Patient)
def create_patient(patient: schemas.PatientCreate, db: Session = Depends(get_db)):
db_patient = models.Patient(**patient.dict())
db.add(db_patient)
db.commit()
db.refresh(db_patient)
return db_patient
이제 여기에 의존성으로 주입된 db 부분과 데이터 형식을 정하기 위한 schema 부분을 알아보자
일단 database.py부터 알아보면,
# database.py
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# SQLite 데이터베이스 사용 (실제 환경에서는 PostgreSQL 등 사용 권장)
SQLALCHEMY_DATABASE_URL = "sqlite:///./healthcare.db"
engine = create_engine(
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
# DB 세션 의존성
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionamker
데이터베이스 URL 설정
SQLALCHEMY_DATABASE_URL = "sqlite:///./healthcare.db"
데이터베이스 엔진 생성
engine = create_engine(
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
세션 팩토리 생성
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
베이스 클래스 생성
Base = declarative_base()
데이터베이스 세션 의존성 함수
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
다음 포스팅에 이어서 schemas.py에 대해서 알아보자
[FastAPI] FastAPI 내부 코드 확인하기 (FastAPI 클래스 생성자 메소드 debug 인자) (0) | 2025.04.17 |
---|---|
[FastAPI] (STT 기능 API 만들기)음성인식 데이터 처리 (WAV to PCM) #1 (0) | 2025.04.16 |
[FastAPI] CRUD 구현 (models.py 중심) #4 (0) | 2025.04.11 |
[FastAPI] CRUD 구현 (schemas.py 부분) #3 (0) | 2025.04.11 |
[FastAPI] CRUD 구현 (Create 하는 법, routers/ 부분 중점) #1 (0) | 2025.04.09 |