使用aiohttp的asyncpg连接池引发asyncpg.exceptions,_base.InterfaceError:无法执行操作:另一个操作正在进行

nukf8bse  于 2022-10-15  发布在  PostgreSQL
关注(0)|答案(1)|浏览(377)

当我尝试使用文档中的aiohttp复制示例时,我收到错误:

asyncpg.exceptions._base.InterfaceError: cannot perform operation: another operation is in progress

当应用程序在任何添加的路由上获取GET请求时引发异常。
以下是我的代码:

import asyncio
import asyncpg
from aiohttp import web

async def handle(request):
    """Handle incoming requests."""
    pool = request.app['pool']
    power = int(request.match_info.get('power', 10))

    # Take a connection from the pool.
    async with pool.acquire() as connection:
        # Open a transaction.
        async with connection.transaction():
            # Run the query passing the request argument.
            result = await connection.fetchval('select 2 ^ $1', power)
            return web.Response(
                text="2 ^ {} is {}".format(power, result))

async def init_app():
    """Initialize the application server."""
    app = web.Application()
    # Create a database connection pool
    app['pool'] = await asyncpg.create_pool(
        host="DB_HOST",
        port=5432,
        user="DB_USER",
        password="DB_PASSWORD",
        database="DB_NAME",)
    # Configure service routes
    app.router.add_route('GET', '/issues', handle)
    app.router.add_route('GET', '/', handle)
    return app

loop = asyncio.get_event_loop()
app = loop.run_until_complete(init_app())
web.run_app(app, port=8800)

如果我使用PgBouler,我会得到同样的结果

6ljaweal

6ljaweal1#

我找到了一个解决方案:
需要在run_app方法中将循环作为参数传递

...
web.run_app(app, port=8800, loop=loop)

相关问题