티스토리 뷰

FastAPI

[FastAPI] SQLAlchemy orm과 schema

PeonyF 2024. 3. 18. 20:43
반응형

ORM(Object-Relational Mapping)

데이터베이스를 사용하려면 SQL 쿼리(query)라는 구조화된 질의를 작성하고 실행하는 등의 복잡한 과정이 필요하다. 이때 ORM(object relational mapping)을 이용하면 파이썬 문법만으로도 데이터베이스를 다룰 수 있다. 즉, ORM을 이용하면 개발자가 쿼리를 직접 작성하지 않아도 데이터베이스의 데이터를 처리할 수 있다.( 점프 투 FastAPI)

 

데이터베이스의 테이블을 파이썬 객체로 매핑하여 SQL 쿼리 없이 데이터베이스와 상호작용할 수 있게 해주는 방식

-> DB의 테이블과 관계를 파이썬 클래스로 정의

sqlalchemy db model 생성

  • declarative_base()  Base class (sqlalchemy model) 생성
  • Base class로부터 상속받아 db 에 해당하는 model class(model) 생성
from sqlalchemy import Boolean, Column, Integer, String
from sqlalchemy.orm import declarative_base

from schema.request import CreateToDoRequest

Base = declarative_base()

'''
ORM: DB Table에 mapping 할 수 있는 형태의 객체를 만들어서 관리하는 방식
직접 SQL 쿼리를 작성하지 않고 파이썬 코드로 SQL쿼리를 생성해 자동으로 연결시켜줌
'''


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}"

    @classmethod
    def create(cls,request:CreateToDoRequest) -> "ToDo":
        return cls(
            contents=request.contents,
            is_done=request.is_done,
        )

 

 

 

 

Schema(Pydantic 모델)

데이터 파싱 과 검증,직렬화,역직렬화를 위해 사용되는 구조. 입력 데이터의 유효성 검사,데이터 변환 등에 사용

-> API로 부터 받은 데이터가 특정 스키마와 일치하는지, 모델에 정의된 타입과 일치하는지 자동 검증

Pydantic Schema 생성

  • pydantic의 BaseModel 모듈 이용
from pydantic import BaseModel
from typing import List


class ToDoSchema(BaseModel):
    id: int
    contents: str
    is_done: bool

    class Config: # 외부 클래스의 동작을 구성하거나 커스터마이징하는 데 사용 주로 이름이 Config,Meta
        # orm_mode = True pydatic v1
        from_attributes = True #ORM 모델로부터 Pydantic 모델로 데이터를 변환할 때 필요한 설정


class ToDoListSchema(BaseModel):
    todos: List[ToDoSchema]

 

 

 

ORM과 Schema를 따로 관리하는 이유

ORM은 db의 table구조와 직접적인 상호작용에사용 (ex.db와의 연동)

Schema는 API의 데이터 구조와 유효성 검사(사용자의 입력이나 API 응답 데이터 형식 정의)

이렇게 분리하여 DB의 내부 구조가 변경되더라도 Schema에 영향을 미치지 않아 결합도를 낮출 수 있음

 

 

진행과정

1. SQLAlchemy를 사용해서 DB모델 정의 및 DB쿼리 실행

  • DB 테이블과 맵핑되는 모델 정의
  • SQLAlchemy세션을 통해 DB쿼리 실행, 결과를 ORM객체로 받음

2. Pydantic모델을 사용하여 데이터 검증 및 직렬화

  • API로 받은 데이터를 Pydantic 모델로 변환하여 데이터의 유효성을 검사
  • SQLAlchemy객체를 Pydantic모델로 변환하여 API response로 리턴
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from pydantic import BaseModel

# SQLAlchemy 모델 정의
Base = declarative_base()
class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    age = Column(Integer)

# Pydantic 모델 정의
class UserSchema(BaseModel):
    id: int
    name: str
    age: int

# SQLAlchemy 세션 생성 및 데이터베이스 쿼리
engine = create_engine('sqlite:///mydatabase.db')
Session = sessionmaker(bind=engine)
session = Session()
user = session.query(User).first()

# SQLAlchemy 객체를 Pydantic 모델로 변환
user_schema = UserSchema.from_orm(user)

 

 

 

실전! FastAPI 입문 - 인프런

https://wikidocs.net/175967

https://wikidocs.net/176222

https://fastapi.tiangolo.com/tutorial/sql-databases/#orms

https://velog.io/@crosstar1228/FastapiSQLAlchemy-%EC%9D%B4%EC%9A%A9%ED%95%98%EC%97%AC-DB%EC%99%80-%EC%97%B0%EA%B2%B0%ED%95%98%EA%B8%B0

반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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
글 보관함