CoWithMe

Flask와 FastAPI에서 PyMySQL과 SQLAlchemy 사용법 비교

이영훈닷컴 2024. 7. 5. 05:35
728x90

Flask와 FastAPI에서 SQLAlchemy를 사용하여 데이터베이스 작업을 수행하는 방법을 비교해 보겠습니다. 두 프레임워크의 사용법은 비슷하지만, 일부 차이점이 있습니다. 각 프레임워크에서의 예시를 통해 쉽게 이해할 수 있도록 정리해보겠습니다.

1. 모델 클래스 상속


Flask : Flask에서는 SQLAlchemy 객체의 Model 클래스를 상속받아 모델 클래스를 정의합니다.

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://user:password@localhost/dbname'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)


FastAPI : FastAPI에서는 SQLAlchemy의 declarative_base()로 생성된 Base 클래스를 상속받아 모델 클래스를 정의합니다.

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

DATABASE_URL = "mysql+pymysql://user:password@localhost/dbname"

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(80), nullable=False)
    email = Column(String(120), unique=True, nullable=False)


2. 세션 관리

 

Flask : Flask에서는 db.session을 통해 세션을 관리합니다.

# Adding a new user in Flask
new_user = User(name="John Doe", email="[email protected]")
db.session.add(new_user)
db.session.commit()


FastAPI : FastAPI에서는 Session 클래스를 직접 사용하여 세션을 초기화하고 관리해야 합니다.

from fastapi import Depends, FastAPI
from sqlalchemy.orm import Session

app = FastAPI()

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@app.post("/users/")
def create_user(name: str, email: str, db: Session = Depends(get_db)):
    new_user = User(name=name, email=email)
    db.add(new_user)
    db.commit()
    db.refresh(new_user)
    return new_user


3. 테이블 생성

 

Flask : Flask에서는 db.create_all()을 통해 모든 테이블을 생성합니다.

with app.app_context():
    db.create_all()


FastAPI : FastAPI에서는 Base.metadata.create_all(bind=engine)을 통해 테이블을 생성합니다.

Base.metadata.create_all(bind=engine)


4. 데이터 추가

 

Flask : Flask에서는 db.session.add()와 db.session.commit()을 사용하여 데이터를 추가합니다.

new_user = User(name="Jane Doe", email="[email protected]")
db.session.add(new_user)
db.session.commit()

 

FastAPI : FastAPI에서는 Session 객체의 add()와 commit() 메서드를 사용하여 데이터를 추가합니다.

def create_user(db: Session, name: str, email: str):
    new_user = User(name=name, email=email)
    db.add(new_user)
    db.commit()
    db.refresh(new_user)
    return new_user


5. 컬럼 정의

 

Flask : Flask에서는 nullable, unique와 같은 추가적인 필드 옵션을 db.Column에서 바로 설정할 수 있습니다.

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)


FastAPI : FastAPI에서도 Column에서 이러한 옵션을 설정할 수 있지만, Pydantic 모델을 통해 추가적인 데이터 유효성 검사를 할 수 있습니다.

from pydantic import BaseModel

class UserCreate(BaseModel):
    name: str
    email: str

@app.post("/users/")
def create_user(user: UserCreate, db: Session = Depends(get_db)):
    new_user = User(name=user.name, email=user.email)
    db.add(new_user)
    db.commit()
    db.refresh(new_user)
    return new_user

 

6. 데이터 타입

 

Flask : Flask에서는 db.Integer, db.String 등을 사용하여 데이터 타입을 명시합니다.

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)


FastAPI : FastAPI에서는 SQLAlchemy의 Integer, String 등을 사용합니다.

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(80), nullable=False)
    email = Column(String(120), unique=True, nullable=False)

 

 

결론

Flask와 FastAPI에서의 SQLAlchemy 사용법은 유사한 측면도 있고, 일부 다른 점도 있습니다. 그러나 FastAPI는 비동기 지원이 뛰어나고, 추가적으로 Pydantic을 통한 데이터 유효성 검사가 가능하므로 복잡한 웹 애플리케이션을 구현할 때 더 많은 이점을 가져갈 수 있습니다.

 

장마철에 먹을 점보 도시락 ^^

728x90