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?
SQLite doesn't support asynchronous I/O. Async ADO.NET methods will execute synchronously in Microsoft.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With