anyio-sqlite

anyio-sqlite is an AnyIO bridge to the standard sqlite3 database module, providing
async versions of all connection, cursor and blob (Python 3.11+) methods that runs
on both asyncio and Trio.
Asynchronous context management is also supported.
Install
anyio-sqlite is compatible with Python 3.9 and newer. Install it from PyPI:
pip install anyio-sqlite
Examples
Use it the same way as the standard sqlite3 module, simply scatter the await keyword when needed:
import anyio
import anyio_sqlite
async def main():
async with anyio_sqlite.connect("example.sqlite3") as con:
async with await con.cursor() as cur:
await cur.execute("CREATE TABLE movie(title, year, score)")
await cur.execute("""
INSERT INTO movie VALUES
('Monty Python and the Holy Grail', 1975, 8.2),
('And Now for Something Completely Different', 1971, 7.5)
""")
await con.commit()
async with await con.execute("SELECT score FROM movie") as cur:
async for row in cur:
...
anyio.run(main)
It can also be used mostly procedurally, if you provide an external task group:
import anyio
import anyio_sqlite
async def main():
async with anyio.create_task_group() as tg:
con = await anyio_sqlite.Connection.connect(tg, "example.sqlite3")
cur = await con.cursor()
await cur.execute("CREATE TABLE movie(title, year, score)")
await cur.execute("""
INSERT INTO movie VALUES
('Monty Python and the Holy Grail', 1975, 8.2),
('And Now for Something Completely Different', 1971, 7.5)
""")
await con.commit()
await cur.aclose()
cur = await con.execute("SELECT score FROM movie")
async for row in cur:
...
await cur.aclose()
await con.aclose()
anyio.run(main)
[!WARNING]
Since each connection spawns a long-running worker in another thread,
the connection must be closed after you're done using it! Otherwise,
the process will hang indefinitely waiting for the worker thread
to finish.
License
Licensed under either of
at your option.