【发布时间】:2020-08-20 02:01:22
【问题描述】:
我想在初始化金字塔应用程序之前做一些数据库检查,但我不太确定该怎么做。
我可能会通过请求工厂创建一个虚假请求并从中获取会话。但我怀疑有更好的方法。我可以从应用程序或配置器中获取临时事务吗?
【问题讨论】:
标签: python sqlalchemy pyramid
我想在初始化金字塔应用程序之前做一些数据库检查,但我不太确定该怎么做。
我可能会通过请求工厂创建一个虚假请求并从中获取会话。但我怀疑有更好的方法。我可以从应用程序或配置器中获取临时事务吗?
【问题讨论】:
标签: python sqlalchemy pyramid
如果您使用的是 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
【讨论】: