【发布时间】:2017-01-26 12:48:02
【问题描述】:
我正在使用 Python 3.5、Pyramid 1.7、uWSGI 2.0.11 和 SQLAlchemy 1.0.9。我听说当使用 uWSGI 和多个 worker 时,我们应该使用 uWSGI postfork 函数来连接到 SQLAlchemy 数据库。否则 SQLAlchemy 将在不同的分叉之间共享连接池,从而导致问题:
按照这个建议,我在文件my_app/__ini__.py 上的金字塔应用程序中添加了这段代码,用于在postfork 事件之后创建连接引擎:
def main(global_config, **settings):
try:
from uwsgidecorators import postfork
except ImportError:
# We're not in a uWSGI context, no need to hook dbs connection
# to the postfork event.
engine = engine_from_config(settings, prefix='sqlalchemy.')
else:
@postfork
def init():
""" Initialize dbs connexions in the context.
Ensures that a new connexion is returned for every new request.
"""
global engine
engine = engine_from_config(settings, prefix='sqlalchemy.')
# Retrieves database connection
def get_db(request):
global engine
connection = engine.connect()
def disconnect(request):
connection.close()
request.add_finished_callback(disconnect)
return connection
config = Configurator(settings=settings, root_factory=my_factory)
config.add_request_method(get_db, 'db', reify=True)
config.scan()
return config.make_wsgi_app()
有经验的人能否确认这是否是在 uWSGI 中使用预分叉的正确方法?我有点困惑,因为我真的不明白是否在引擎创建期间或调用engine.connect()时定义了与某个池的连接@
【问题讨论】:
标签: python-3.x sqlalchemy pyramid uwsgi