pip install sqlalchemy
orm 다운
pip install pymysql
파이썬과 mysql 을 연동할 때 사용하는 드라이버
pip install cryptography
pymysql 을 통해 mysql 접속할 때 인증이나 암호 관련 처리를 해주는 라이브러리
✔️ Database 연결
database > connection.py
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
DATABASE_URL = "mysql+pymysql://root:todos@127.0.0.1:3306/todos"
engine = create_engine(DATABASE_URL, echo=True)
SessionFactory = sessionmaker(autocommit=False, autoflush=False, bind=engine)
✔️ ORM 설정
database > orm.py
from sqlalchemy import Boolean, Column, Integer, String
from sqlalchemy.orm import declarative_base
Base = declarative_base()
class ToDo(Base):
__tablename__ = "todo"
id = Column(Integer, primary_key=True, index=True)
contents = Column(String(256), nullable=False)
is_done = Column(Boolean, nullable=False)
def __repr__(self):
return f"ToDo(id={self.id}, contents={self.contents}, is_done={self.is_done})"
데이터베이스 테이블을 클래스처럼 사용하기 위해서 위처럼 설정이 가능하다.
'컴퓨터 프로그래밍 > FastAPI' 카테고리의 다른 글
[FastAPI] Redis 를 활용해 otp 기능 구현 (0) | 2025.03.17 |
---|---|
[Alembic] Alembic (0) | 2025.03.15 |
[FastAPI] Repository 패턴 및 orm 적용 (0) | 2025.03.15 |
[FastAPI] Status_code Error 처리 (0) | 2025.03.14 |
[FastAPI] CRUD (0) | 2025.03.13 |