본문 바로가기
C.W.K.
Stream
Lesson 02 of 10 · published

aiosqlite — Async Wrapper

~12 min · aiosqlite, async, wrapper

Level 0Scout
0 XP0/80 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

API는 그대로, await만 뿌리면 돼

aiosqlite는 표준 sqlite3 모듈을 감싸서 모든 연산을 await할 수 있게 만들어. 안에서는 connection마다 백그라운드 thread를 하나씩 두고 호출을 거기로 밀어 넣어. 그래서 event loop가 절대 멈추지 않아.

pip install aiosqlite

기억할 모양은 다섯이야.

  • aiosqlite.connect(path) — connection을 내주는 async context manager야.
  • conn.execute(sql, params) — async cursor를 돌려줘.
  • await cursor.fetchone()await cursor.fetchall()로 결과를 꺼내.
  • async for row in conn.execute(...)로 흘려 받으며 순회해.
  • conn.row_factory = aiosqlite.Row로 sync sqlite3와 똑같이 dict처럼 다뤄.
Tip: sync sqlite3에서 걸던 PRAGMA를 여기서도 똑같이 걸어. WAL, foreign_keys, busy_timeout 다. aiosqlite가 밑에 있는 connection에 그대로 넘겨줘.

Code

Hello, aiosqlite·python
import asyncio, aiosqlite

async def main():
    async with aiosqlite.connect('demo.db') as conn:
        conn.row_factory = aiosqlite.Row
        await conn.execute('PRAGMA journal_mode = WAL')
        await conn.execute('PRAGMA foreign_keys = ON')
        await conn.execute(
            'CREATE TABLE IF NOT EXISTS notes(id INTEGER PRIMARY KEY, body TEXT)'
        )
        await conn.execute('INSERT INTO notes(body) VALUES (?)', ('hello',))
        await conn.commit()

        async with conn.execute('SELECT * FROM notes') as cur:
            async for row in cur:
                print(dict(row))

asyncio.run(main())

External links

Exercise

sync sqlite3로 짜둔 스크립트를 하나 골라 aiosqlite로 옮겨봐. 옮기는 일이 거의 기계적이라는 걸 확인하게 될 거야. async와 await를 붙이고, context manager로 바꾸고, row factory를 갈아끼우면 끝이거든. 그다음 작은 동시성 테스트를 해봐. 같은 DB에 짧은 query를 던지는 async task를 100개 띄우고, sync sqlite3에 thread를 쓴 경우와 비교해.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.