我有这个Pyramid应用程序:
from pyramid.config import Configurator
from pyramid.response import Response
from sqlalchemy import create_engine
from sqlalchemy.pool import QueuePool
from sqlalchemy.sql import text
POOL_SIZE = 10
try:
import uwsgi
POOL_SIZE = int(uwsgi.opt['threads'])
def postfork():
engine.dispose()
uwsgi.post_fork_hook = postfork
except ImportError:
pass
DBURL = 'postgres://postgres:pass@127.0.0.1:5455/postgres'
engine = create_engine(DBURL, poolclass=QueuePool, pool_size=POOL_SIZE)
def db_conn(request):
conn = engine.contextual_connect()
def cleanup(request):
conn.close()
request.add_finished_callback(cleanup)
return conn
def some_view(request):
conn = request.db_conn
with conn.begin() as trans:
s = text('SELECT 1')
cur = conn.execute(s)
result = cur.first()
return Response('<h1>{}</h1>'.format(result))
def main():
config = Configurator()
config.add_request_method(db_conn, reify=True)
config.add_route('some_view', '/')
config.add_view(some_view, route_name='some_view')
app = config.make_wsgi_app()
return app
application = main()
我正在使用uWSGI运行的:
uwsgi --wsgi-file webapp.py --http :9090 --master --processes 2 --threads 2
我的主要问题是该代码是否正确。我可以确定不同的进程/线程将使用不同的连接吗?
我有2个进程,每个进程有2个线程,我的假设是:
在uWSGI后叉挂钩中调用
engine.dispose()
可确保每个进程都有自己的连接调用
config.add_request_method(db_conn, reify=True)
会将SQLAlchemy连接对象添加到请求中。在后台使用本地线程来确保线程之间的不同连接我得到的连接调用的是
contextual_connect()
而不是connect()
,但是我认为使用哪种方法都没有关系。但是我不确定它们是否正确,特别是第二种。
最后一点,我知道SQLAlchemy的
scoped_session
和sessionmaker
,但是我想直接使用连接对象来更好地了解它的工作方式。 最佳答案
我没有发现您的示例代码有什么问题。我也同意,我认为您应该只使用connect()
而不是contextual_connect()
。
关于python - 如何使用uWSGI和Pyramid确保唯一的SQLAlchemy数据库连接,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40835653/