[python] Peewee를 사용한 비동기 프로그래밍

Peewee는 파이썬으로 작성된 간단하고 가벼운 ORM(Object Relational Mapper) 라이브러리입니다. 기존의 동기식 프로그래밍에서 비동기 프로그래밍으로 전환하기 위해 asyncio와 함께 사용할 수 있습니다. 이번 글에서는 Peewee를 사용하여 비동기 프로그래밍을 어떻게 구현하는지 살펴보겠습니다.

1. Peewee 비동기 버전 설치하기

Peewee의 비동기 버전은 peewee-async 패키지로 제공됩니다. 이 패키지를 설치하기 위해 다음 명령어를 터미널에 입력합니다.

pip install peewee-async

2. 비동기 데이터베이스 연결 설정하기

먼저, 비동기 데이터베이스 연결을 설정해야 합니다. Peewee의 비동기 버전에서는 AsyncMySQLDatabase 또는 AsyncPostgresqlDatabase 클래스를 사용하여 MySQL 또는 PostgreSQL과 같은 데이터베이스에 연결할 수 있습니다. 다음은 MySQL에 연결하는 예제입니다.

from peewee_async import AsyncMySQLDatabase
from peewee import Model, CharField

db = AsyncMySQLDatabase(
    'database_name',
    user='user',
    password='password',
    host='localhost',
    port=3306
)


class BaseModel(Model):
    class Meta:
        database = db


class User(BaseModel):
    username = CharField()
    password = CharField()

db.set_allow_sync(False)
db.connect()

3. 비동기 쿼리 실행하기

비동기 프로그래밍에서 쿼리는 asyncio의 코루틴을 사용하여 실행됩니다. 이를 위해 Peewee의 비동기 버전에서는 async def 키워드를 사용하여 비동기 함수를 정의합니다. 다음은 사용자 테이블에서 모든 레코드를 가져오는 예제입니다.

async def get_users():
    query = User.select()
    users = await db.execute(query)
    return users

users = asyncio.run(get_users())

위 예제에서 db.execute() 메서드를 사용하여 비동기 쿼리를 실행하고, 그 결과인 users를 반환합니다.

4. 비동기 트랜잭션 처리하기

Peewee의 비동기 버전에서는 비동기로 트랜잭션을 처리할 수 있습니다. 트랜잭션이 필요한 부분에서는 async with 문을 사용하여 비동기 트랜잭션을 시작하고, commit() 또는 rollback() 메서드를 사용하여 트랜잭션을 완료합니다.

async with db.atomic_async():
    # 트랜잭션 처리가 필요한 작업
    await do_something()
    ...
    await another_operation()
    ...
    db.commit()

5. Peewee 비동기 모델 사용하기

Peewee의 비동기 버전에서는 async def를 사용하여 비동기 메서드를 정의할 수 있습니다. 다음은 사용자 테이블에 새로운 레코드를 추가하는 예제입니다.

class User(BaseModel):
    username = CharField()
    password = CharField()

    async def create_user(self, username, password):
        user = User(username=username, password=password)
        await self.save()
        return user

user = asyncio.run(User.create_user("john", "password"))

위 예제에서 create_user() 메서드는 비동기로 정의되어 있으며, await self.save()를 통해 새로운 레코드를 데이터베이스에 저장합니다.

마무리

이번 글에서는 Peewee를 사용한 비동기 프로그래밍에 대해 알아보았습니다. Peewee를 활용하여 비동기 프로그래밍을 구현하면 데이터베이스 작업을 효율적으로 처리할 수 있습니다. Peewee-async의 공식 문서를 참조하여 추가적인 사용법을 알아보세요.