【问题标题】:How to get a db session at Pyramid app initialisation如何在 Pyramid 应用程序初始化时获取数据库会话
【发布时间】:2020-08-20 02:01:22
【问题描述】:

我想在初始化金字塔应用程序之前做一些数据库检查,但我不太确定该怎么做。

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

【问题讨论】:

    标签: python sqlalchemy pyramid


    【解决方案1】:

    如果您使用的是 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-11
      • 2021-01-24
      • 2021-11-23
      • 1970-01-01
      • 2023-01-27
      • 2011-06-10
      • 2016-05-28
      • 1970-01-01
      相关资源
      最近更新 更多