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 가 standard sqlite3 모듈 wrap, 모든 연산 await 가능. 내부에서 connection 마다 single 백그라운드 thread 에 호출 push — event loop 절대 block 안 됨.

pip install aiosqlite

중요한 모양:

  • aiosqlite.connect(path) — connection yield 하는 async context manager.
  • conn.execute(sql, params) — async cursor 반환.
  • await cursor.fetchone(), await cursor.fetchall().
  • async for row in conn.execute(...) — streaming iteration.
  • conn.row_factory = aiosqlite.Row — sync sqlite3 와 같은 dict-like row.
Tip: Sync sqlite3 에 설정한 같은 PRAGMA — WAL, foreign_keys, busy_timeout — 설정. aiosqlite 가 underlying connection 에 그대로 forward.

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 로 port. API 변환이 mostly mechanical 확인 (async/await 추가, context manager 전환, row factory 교체). 그 다음 작은 동시성 테스트: 같은 DB 에 짧은 query 100 async task. Sync sqlite3 + thread 와 비교.

Progress

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

댓글 0

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

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