【问题标题】:SQLAlchemy core + Pyramid not closing connectionsSQLAlchemy核心+金字塔不关闭连接
【发布时间】:2016-10-21 06:52:39
【问题描述】:

我有 SQLAlchemy CORE 1.0.9 和 Pyramid 框架 1.7。我正在使用以下配置连接到 postgres 9.4 数据库:

# file __ini__.py
from .factories import root_factory
from pyramid.config import Configurator
from sqlalchemy import engine_from_config


def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application."""

    config = Configurator(settings=settings, root_factory=root_factory)
    engine = engine_from_config(settings, prefix='sqlalchemy.')

    # Retrieves database connection
    def get_db(request):
        connection = engine.connect()
        def disconnect(request):
            connection.close()
        request.add_finished_callback(disconnect)
        return connection

    config.add_request_method(get_db, 'db', reify=True)
    config.scan()
    return config.make_wsgi_app()

使用该应用几个小时后,我开始收到以下错误:

sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) FATAL:  remaining connection slots are reserved for non-replication superuser connections

显然我已达到最大连接数。似乎 connections.close() 并没有真正关闭连接,只是将连接返回到池中。我知道我可以使用 NullPool 来禁用池,但这可能会对性能产生巨大影响。

有人知道配置 SQLAlchemy Core 以获得良好性能并正确关闭连接的正确方法吗?

请不要向pyramid tutorials 发送链接。我对 SQLAlchemy ORM 设置不感兴趣。请只使用 SQLAlchemy Core

【问题讨论】:

  • 我认为您应该使用 Zope 事务管理器 (pyramid_tm)。这是与请求处理集成的 Pyramid 应用程序的包装器。如果请求顺利完成,它会自动提交事务;或者,如果出现异常,它将中止事务。 More Info
  • FWIW 我看不出您的示例代码有什么问题。 ORM 有Session.remove 以确保真正删除了东西,但是使用 SQLA 核心,.close 应该可以工作。

标签: sqlalchemy pyramid


【解决方案1】:

实际上,在之前的设置中一切都很好。该问题是由 Celery 工作人员未关闭连接引起的。

【讨论】:

  • 我对芹菜也有类似的问题。你是怎么解决这个问题的?我在 GCP 上设置 airflow 时遇到了这个问题
猜你喜欢
  • 2013-11-23
  • 2014-09-01
  • 2014-04-20
  • 1970-01-01
  • 2023-01-26
  • 2015-09-21
  • 2014-01-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多