약 6분
본문 듣기
읽기 설정
글자 크기
줄 간격
글꼴
7.3 FastAPI와 SQLAlchemy로 데이터베이스 연동하기
이번 장에서는 FastAPI와 SQLAlchemy를 활용하여 데이터베이스를 연동하는 방법을 배우겠습니다. FastAPI는 Python으로 쉽게 API를 작성할 수 있게 해주는 프레임워크이고, SQLAlchemy는 객체 관계 매핑(ORM) 도구로 데이터베이스와의 상호작용을 간편하게 제공합니다. 아래 단계별 가이드를 통해 데이터베이스에 간단한 CRUD(Create, Read, Update, Delete) 연산을 수행하는 웹 API를 구축해 보겠습니다.
실습 프로젝트 개요
이번 실습에서는 SQLite 데이터베이스를 사용하여 사용자 정보를 관리하는 API를 구현합니다. API는 다음과 같은 기본적인 기능을 제공합니다:
- 사용자 추가하기
- 사용자 정보 조회하기
- 사용자 정보 수정하기
- 사용자 삭제하기
Step 1: FastAPI 및 SQLAlchemy 설치하기
먼저 FastAPI와 SQLAlchemy를 설치해야 합니다. 다음 명령어를 터미널에 입력하여 설치합니다:
pip install fastapi sqlalchemy uvicorn psycopg2
Step 2: FastAPI 애플리케이션 세팅하기
이제 FastAPI 애플리케이션을 작성합니다. 아래 코드를 참고하세요:
코드
python
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
app = FastAPI()
# Database 설정
DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, index=True)
email = Column(String, unique=True, index=True)
Base.metadata.create_all(bind=engine)
# Pydantic 모델 정의
class UserCreate(BaseModel):
name: str
email: str
class UserOut(BaseModel):
id: int
name: str
email: str
class Config:
orm_mode = True
# CRUD 작업
@app.post("/users/", response_model=UserOut)
async def create_user(user: UserCreate):
db = SessionLocal()
db_user = User(name=user.name, email=user.email)
db.add(db_user)
db.commit()
db.refresh(db_user)
db.close()
return db_user
@app.get("/users/{user_id}", response_model=UserOut)
async def read_user(user_id: int):
db = SessionLocal()
db_user = db.query(User).filter(User.id == user_id).first()
db.close()
if db_user is None:
raise HTTPException(status_code=404, detail="User not found")
return db_user
댓글 0
아직 댓글이 없습니다. 첫 댓글을 남겨보세요.