[英]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.