如何处理 Sqlalchemy 中的 asyncpg.exceptions.TooManyConnectionsError

voi*_*lex 5 postgresql sqlalchemy exception python-asyncio asyncpg

我正在开发一个使用异步 SQLAlchemy 连接asyncpg到 PostgreSQL 数据库的项目。问题是这样的:当我与数据库建立太多连接时,它会引发以下异常:

asyncpg.exceptions.TooManyConnectionsError: sorry, too many clients already
Run Code Online (Sandbox Code Playgroud)

这基本上是 Postgres 本身和配置的限制。但遗憾的是,会话无法处理此问题,例如尝试多次连接。是否有任何解决方法可以使其无异常地工作?

这是设置:

asyncpg.exceptions.TooManyConnectionsError: sorry, too many clients already
Run Code Online (Sandbox Code Playgroud)

voi*_*lex 1

我想出了以下解决方法:

...

AsyncSessionBase = async_scoped_session(async_session_factory, scopefunc=current_task)

@asynccontextmanager
async def AsyncSession(max_trials=12):
    for i in range(max_trials):
        try:
            async with AsyncSessionBase() as session:
                yield session
        except asyncpg.exceptions.TooManyConnectionsError:
            continue
        return
Run Code Online (Sandbox Code Playgroud)

它会尝试创建指定次数的会话,并且只有在这之后才会引发异常。asyncpg.exceptions.TooManyConnectionsError是它处理的唯一异常,因此不会影响其他异常的逻辑。

但我仍然不知道是否有原生的 sqlalchemy 解决方案。