我使用 aiogram 库编写异步电报机器人。我决定使用 SQLite 作为存储不可变值的数据库。如何从我的数据库中实现异步读取?
sqlite3
模块的包装已经存在,你应该在你的异步代码中使用它。
run_in_executor
中将它们转换为异步调用。例如:
async def fetchall_async(conn, query):
loop = asyncio.get_event_loop()
return await loop.run_in_executor(
None, lambda: conn.cursor().execute(query).fetchall())
这为您提供了一个可以从异步代码中调用的协程,而不必担心长时间运行的执行会阻塞整个事件循环:
async def some_task():
...
students = await fetchall_async(conn, "select * from students")
但是把它留给一个经过良好测试的包是一个更好的主意。