Python 如何在金字塔应用程序初始化时获得db会话
在启动金字塔应用程序之前,我想做一些数据库检查,但我不太确定如何做Python 如何在金字塔应用程序初始化时获得db会话,python,sqlalchemy,pyramid,Python,Sqlalchemy,Pyramid,在启动金字塔应用程序之前,我想做一些数据库检查,但我不太确定如何做 我可能会通过请求工厂创建一个假请求,并从中获取会话。但我怀疑还有更好的办法。我可以从应用程序或配置程序中获取临时事务吗?如果您使用cookiecutter,那么它非常简单。会话工厂存储在config.registry['dbsession\u factory']中,您可以随时获取它并使用它创建会话,包括在配置时。一个好方法是使用临时事务管理器,但这不是必需的 import transaction from myapp.mode
我可能会通过请求工厂创建一个假请求,并从中获取会话。但我怀疑还有更好的办法。我可以从应用程序或配置程序中获取临时事务吗?如果您使用cookiecutter,那么它非常简单。会话工厂存储在
config.registry['dbsession\u 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
如果您使用的是cookiecutter,那么它非常简单。会话工厂存储在
config.registry['dbsession\u 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