[python] Marshmallow의 exclude 기능을 사용하여 특정 필드 제외하기

Marshmallow는 Python에서 객체 직렬화와 역직렬화를 쉽게 처리할 수 있는 라이브러리입니다. Marshmallow 스키마를 사용하면 Python 객체를 JSON 또는 다른 형식으로 변환할 수 있습니다.

Marshmallow의 exclude 기능을 사용하면 Marshmallow 스키마에 정의된 필드 중에서 특정 필드를 제외할 수 있습니다. 이를 통해 필요한 필드만 직렬화 또는 역직렬화할 수 있습니다.

다음은 Marshmallow의 exclude 기능을 사용하여 특정 필드를 제외하는 예제 코드입니다.

from marshmallow import Schema, fields, post_load

class User:
    def __init__(self, name, email):
        self.name = name
        self.email = email

class UserSchema(Schema):
    name = fields.Str()
    email = fields.Email()

    @post_load
    def make_user(self, data, **kwargs):
        return User(**data)

# exclude를 사용하여 email 필드를 제외한 스키마 생성
user_schema = UserSchema(exclude=('email',))

# 직렬화
user = User('John Doe', 'johndoe@example.com')
result = user_schema.dumps(user)
print(result)  # {"name": "John Doe"}

# 역직렬화
data = '{"name": "Jane Doe", "email": "janedoe@example.com"}'
result = user_schema.loads(data)

print(result.name)  # Jane Doe
print(result.email)  # AttributeError: 'UserSchema' object has no attribute 'email'

위 코드에서는 UserSchema 클래스의 exclude 매개변수를 사용하여 email 필드를 제외한 스키마를 생성합니다. dumps 메서드를 사용하여 객체를 직렬화하면 제외된 필드가 결과에 포함되지 않습니다. 마찬가지로 loads 메서드를 사용하여 객체를 역직렬화하면 제외된 필드는 무시됩니다.

이렇게 Marshmallow의 exclude 기능을 사용하여 특정 필드를 제외하면 필요한 데이터만 처리할 수 있습니다.


참조: