Issue
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?
Solution
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.
Answered By - user4815162342
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.