2

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.

2
  • I believe it doesn't work at all right? Commented Oct 13, 2018 at 3:17
  • 1
    That's not how it works. The answer is you can't make async queries that way. For one thing, the method after the await must return an "awaitable", such as a coroutine. You could use threads to parallelize this . Commented Oct 13, 2018 at 3:49

1 Answer 1

2

You really misunderstood async. You should first have an async lib to get async support. Obviously MySQLdb is not.

Take a look at https://github.com/aio-libs/aiomysql

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.