[英]Closing a connection in Python with asyncio
我正在尝试从数据库中检索数据以在 api 上下文中使用。 但是我注意到 conn.close() 执行时间相对较长(在这种情况下,conn 是来自 mysql 连接池的连接)。 由于关闭连接不会阻止 api 返回数据的能力,我想我会使用 asyncio 异步关闭连接,这样它就不会阻止返回的数据。
async def get_data(stuff):
conn = api.db.get_connection()
cursor = conn.cursor(dictionary=True)
data = execute_query(stuff, conn, cursor)
cursor.close()
asyncio.ensure_future(close_conn(conn))
return helper_rows
async def close_conn(conn):
conn.close()
results = asyncio.run(get_data(stuff))
然而,尽管事实上 asyncio.ensure_future(close(conn)) 并没有阻塞(我放入计时语句以查看所有内容花费了多长时间,并且该命令之前和之后的那些大约 1ms 不同)实际结果不会是直到 close_conn 完成。 (我使用时间语句验证了这一点,以及它到达 get_data 中的 return 语句与 results=asyncio.run(get_data(stuff)) 之后的行之间的时间差约为 200 毫秒)。
所以我的问题是如何让这段代码在后台关闭连接,这样我就可以自由地提前 go 并处理数据而无需等待。
由于conn.close()
不是协程,它会在close_conn
被调度时阻塞事件循环。 如果您想做您所描述的,请使用异步 sql 客户端并执行await conn.close()
。
您可以尝试使用异步上下文管理器。 (与语句异步)
async def get_data(stuff):
async with api.db.get_connection() as conn:
cursor = conn.cursor(dictionary=True)
data = execute_query(stuff, conn, cursor)
cursor.close()
asyncio.ensure_future(close_conn(conn))
return helper_rows
results = asyncio.run(get_data(stuff))
如果这不起作用,请尝试使用 aiosqlite 的 sql 客户端。
https://github.com/omnilib/aiosqlite
import aiosqlite
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.