Creating a connection pool in aiohttp with aiomysql

1k views Asked by At

I need to be able access an aiomysql connection pool within the aiohttp app like so

async def get(request):
    async with request.app['db'].acquire() as conn:
        async with connection.cursor() as cur:
            await cur.execute('SELECT ...')
            rows = await cur.fetchall()
            return web.json_response(rows)

To keep the connection pool in the app, I know I need to do something like

app = web.Application()
loop = asyncio.get_event_loop()
app['db'] = aiomysql.create_pool(db='...', user='...', password='...', loop=loop)
app.add_routes(routes)
web.run_app(app)

However, this obviously fails because aiomysql.create_pool is a coroutine. What's the correct syntax here?

1

There are 1 answers

0
Wasif Tanveer On

I know its late but hopefully it can help someone, you can create pool by following

import aiomysql

async def init_db(app):
    pool = await aiomysql.create_pool(host='host', port=2222),
                                  user='user', password='password',
                                  db='dbname')
app['mysql_db'] = pool

and then you can use the pool to get connections

    async def someApi(request):
      pool = request.app["mysql_db"]
      async with pool.acquire() as conn:
        async with conn.cursor() as cur:
           await cur.execute("select * from table")
           rows = await cur.fetchall()