Search code examples
pythonsqlalchemythread-safetypyramid

Thread safe SQLAlchemy session for Pyramid requests


The article What the Zope Transaction Manager Means To Me (and you), demonstrates a nice way to attach an SQLAlchemy DB session to each request this way:

def includeme(config):
    settings = config.get_settings()
    engine = engine_from_config(settings)

    maker = sessionmaker()
    register(maker)
    maker.configure(bind=engine)

    config.add_request_method(lambda request: maker(), 'db_session', reify=True)

The problem with this approach is that "the transaction manager is still provided as a threadlocal under this design". Any idea how to fix it? Thanks!


Solution

  • https://gist.github.com/mmerickel/84b34ee5d68ed20dae10#file-model-py-L16-L19 Thanks to some improvements in the pyramid_tm package you can actually completely remove the threadlocal transaction manager. Whether that is a good idea or not is up to you.