Async SQLite python

dydoser picture dydoser · Oct 6, 2018 · Viewed 8.5k times · Source

I write asynchronous telegram bot using the aiogram library. I decided to use SQLite as a database for storing immutable values. How do I implement asynchronous reads from my database?

Answer

user4815162342 picture user4815162342 · Oct 6, 2018

A wrapper for the sqlite3 module already exists, and you should use it in your async code.

Alternatively, you can turn synchronous calls into asynchronous ones by wrapping them in run_in_executor. For example:

async def fetchall_async(conn, query):
    loop = asyncio.get_event_loop()
    return await loop.run_in_executor(
        None, lambda: conn.cursor().execute(query).fetchall())

That gives you a coroutine you can call from your async code without worrying that a long-running execution will block the whole event loop:

async def some_task():
    ...
    students = await fetchall_async(conn, "select * from students")

But it is a much better idea to leave this to a well-tested package.