[python] Marshmallow의 데이터베이스 관련 확장 기능 사용하기

Marshmallow는 파이썬에서 사용하는 데이터 직렬화 및 역직렬화 라이브러리입니다. 이 라이브러리는 개체를 JSON이나 다른 형식으로 변환하고, 변환된 데이터를 다시 원래 개체 형식으로 되돌릴 수 있습니다. 이번 포스트에서는 Marshmallow를 사용하여 데이터베이스 관련 확장 기능을 다루어보겠습니다.

Marshmallow-SQLAlchemy 라이브러리 설치하기

Marshmallow-SQLAlchemy는 SQLAlchemy와 Marshmallow를 결합한 확장 라이브러리입니다. 이를 사용하면 SQLAlchemy 모델을 기반으로 자동으로 스키마를 생성하고, 데이터베이스 동작을 형식화할 수 있습니다. Marshmallow-SQLAlchemy를 설치하기 위해서는 다음 명령을 실행합니다:

pip install marshmallow-sqlalchemy

SQLAlchemy 모델 정의하기

Marshmallow-SQLAlchemy를 사용하려면 SQLAlchemy 모델을 정의해야 합니다. 예를 들어, 사용자(User)를 나타내는 SQLAlchemy 모델을 다음과 같이 정의할 수 있습니다:

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    username = Column(String)
    email = Column(String)
    password = Column(String)

Marshmallow 스키마 정의하기

Marshmallow-SQLAlchemy는 SQLAlchemy 모델로부터 Marshmallow 스키마를 자동으로 생성합니다. 다음은 위에서 정의한 User 모델에 대한 Marshmallow 스키마의 예입니다:

from marshmallow_sqlalchemy import SQLAlchemySchema, auto_field

class UserSchema(SQLAlchemySchema):
    class Meta:
        model = User

    id = auto_field()
    username = auto_field()
    email = auto_field()

데이터 직렬화 및 역직렬화하기

Marshmallow를 사용하여 데이터를 직렬화하거나 역직렬화하는 방법은 간단합니다. 다음은 사용자 객체를 직렬화하고, 역직렬화하는 방법을 보여주는 예입니다:

from marshmallow import Schema, fields

# 직렬화
user = UserSchema().dump(User.query.first())
print(user)

# 역직렬화
data = {
    'username': 'john',
    'email': 'john@example.com',
    'password': 'password123'
}
new_user = UserSchema().load(data)

위 예제에서 User.query.first()는 SQLAlchemy에서 첫 번째 사용자를 가져오는 예제입니다.

Marshmallow를 사용하여 데이터베이스 관련 확장 기능을 사용하는 방법을 알아보았습니다. Marshmallow-SQLAlchemy를 사용하면 SQLAlchemy 모델을 기반으로 스키마를 생성하고, 데이터를 손쉽게 직렬화하거나 역직렬화할 수 있습니다. 더 자세한 내용은 Marshmallow-SQLAlchemy의 공식 문서를 참고하시기 바랍니다.

참고 자료