我正在尝试了解asyncio
以及如何将它与MySQLdb一起使用。我想我只是不明白 asyncio 是如何工作的。例如,假设我想同时异步执行两个查询。例如,如果没有异步,我正在执行两个查询,那么我可能会这样做
import MySQLdb
def test1():
conn = MySQLdb.connect('host', 'user', 'password', 'db')
conn.query('FIND * FROM table1')
return conn.store_result().fetch_row(numrows=0, how=1)
conn.close()
def test1():
conn = MySQLdb.connect('host', 'user', 'password', 'db')
conn.query('FIND * FROM table2')
return conn.store_result().fetch_row(numrows=0, how=1)
conn.close()
if __name__ == '__main__':
foo1 = test1()
foo2 = test2()
这很慢,因为它需要在启动 test2()
之前完成来自 test1()
的查询。我的理解是,这就是 asyncio 提供帮助的地方,因为它可以启动一个函数,然后放开控制权来执行第二个函数。我以为你是通过使用 async
将函数变成异步函数来做到这一点,然后用 await
表示在函数中等待的位置,但我很确定我是误解了这一点。这就是我正在尝试做的事情:
import asyncio
import MySQLdb
async def test1():
conn = await MySQLdb.connect('host', 'user', 'password', 'db')
await conn.query('FIND * FROM table1')
conn.close()
return conn.store_result().fetch_row(numrows=0, how=1)
async def test1():
conn = await MySQLdb.connect('host', 'user', 'password', 'db')
await conn.query('FIND * FROM table2')
conn.close()
return conn.store_result().fetch_row(numrows=0, how=1)
if __name__ == '__main__':
loop = sayncio.get_event_loop()
loop.run_until_complete(asyncio.gather(test1(), test2()))
loop.close()
这行不通。有没有办法用MySQLdb以这种方式进行异步查询?我使用的是 Python 3.6。
最佳答案
你真的误解了异步。您首先应该有一个异步库来获得异步支持。显然 MySQLdb
不是。
关于python - 将 asyncio 与 MySQLdb 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52788956/