如何在Pyramid应用程序初始化时获取数据库会话

问题描述 投票:0回答:1

我想在启动金字塔应用程序之前进行一些数据库检查,但是我不太确定该怎么做。

我可能会通过请求工厂创建一个虚假请求并从中获取会话。但是我怀疑还有更好的方法。我可以从应用程序或配置程序获得临时交易吗?

python sqlalchemy pyramid
1个回答
0
投票

如果您使用的是cookiecutter,则非常简单。会话工厂存储在config.registry['dbsession_factory']中,您可以随时获取它并使用它进行会话,包括在配置时。一个很好的方法是使用临时事务管理器,但这不是必需的。

import transaction

from myapp.models import get_tm_session

def main(...):
    config.include('myapp.models')
    tm = transaction.TransactionManager(explicit=True)
    with tm:
        dbsession = get_tm_session(config.registry['dbsession_factory'], tm)
        # do stuff, the "with tm" will invoke commit if there are no exceptions
© www.soinside.com 2019 - 2024. All rights reserved.