0
我有SQLAlchemy核心1.0.9与金字塔框架1.7。我现在用的是下面的配置用于连接到一个Postgres 9.4数据库:SQLAlchemy核心+金字塔不关闭连接
# 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)。这是一个与您的金字塔应用程序相关的包装,与请求处理集成在一起。如果请求完成而没有发生事件,它会自动提交事务;或者,如果出现异常,它会中止交易。 [更多信息](http://pyramid-sqlalchemy.readthedocs.io/en/latest/transactions.html) – webjunkie
FWIW我没有看到你的示例代码有什么问题。 ORM具有'Session.remove'来确保事物被删除,但是使用SQLA核心,'.close'应该可以工作。 –