【发布时间】: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