I'm trying to understand asyncio and how to use it with MySQLdb. I think I just don't understand how asyncio works. For example, let's say I want to asynchronously do two queries at the same time. For example, without async and I'm doing two queries then I might do it like
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()
And this is slow because it needs to finish the query from test1() before even starting test2(). My understanding is that this is where asyncio helps because it can start a function and then let go control to do a second function. I thought you did this by making a function into an asynchronous function using async and then said where to wait in the function with await, but I'm pretty sure I'm misunderstanding that. This is what I am trying to do:
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()
And this doesn't work. Is there a way to make asynchronous queries with MySQLdb in this way? I'm using Python 3.6.
awaitmust return an "awaitable", such as a coroutine. You could use threads to parallelize this .