【问题标题】:Creating a connection pool in aiohttp with aiomysql使用 aiomysql 在 aiohttp 中创建连接池
【发布时间】:2020-10-18 16:24:36
【问题描述】:

我需要能够像这样访问 aiohttp 应用程序中的 aiomysql 连接池

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)

为了将连接池保留在应用程序中,我知道我需要执行类似的操作

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)

但是,这显然失败了,因为 aiomysql.create_pool 是一个协程。这里的正确语法是什么?

【问题讨论】:

  • 你应该考虑aiohttp signals
  • @ArtemiyRodionov 非常棒。 app.on_startup.append 是我需要的。

标签: python python-asyncio aiohttp aio-mysql


【解决方案1】:

我知道它已经晚了,但希望它可以帮助某人, 您可以通过以下方式创建池

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

然后你可以使用池来获取连接

    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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-28
    • 2016-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-14
    相关资源
    最近更新 更多