Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async SQLite python [closed]

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?

like image 880
dydoser Avatar asked Oct 06 '18 18:10

dydoser


People also ask

Does SQLite support async?

SQLite doesn't support asynchronous I/O. Async ADO.NET methods will execute synchronously in Microsoft.

What happens if you don't close SQLite connection?

If you leave it open, it stays open until it goes out of scope and garbage collected. At that point it might be safely closed (and I believe sqlite3 does that). But better to be safe than sorry. Close your connections when you will no longer use them.

What is Asyncio run?

asyncio. run(main()) asyncio is a library to write concurrent code using the async/await syntax. asyncio is used as a foundation for multiple Python asynchronous frameworks that provide high-performance network and web-servers, database connection libraries, distributed task queues, etc.


1 Answers

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.

like image 171
user4815162342 Avatar answered Sep 30 '22 05:09

user4815162342