Question

I am writing a library for Pyramid. One aspect involves the library being provided with a model class, then retrieving all instances of the model from the database. However, I am unable to interact with the DB without access to the session factory.

In Django this was taken care of behind the scenes. With Pyramid & SQLAlchemy this is not the case.

Is there a standard way for me to get hold of the current thread's DB Session within Pyramid, and without having any knowledge of how a particular project is setup (as this is a reusable library)?

PS. I'm still getting my head around this area of SQLAlchemy, so please excuse any confusion.

Was it helpful?

Solution

You could specify sqla session as attribute in inherited classes, like factory-boy does: https://factoryboy.readthedocs.org/en/latest/orms.html?highlight=sqlalchemy#sqlalchemy

Another way is create interface and require to register sqlalchemy session in application registry as utility, before "config.include" your extension. Maybe pyramid_jinja2 will clarify this solution.

OTHER TIPS

I recommend reading about

a convention to add session to the request object. Your library makes just an assumption about that and write that in your package docs.

Global vs. Non-Global session

A offical tutorial showing those concepts

A lot of pyramid applications use the package zope.sqlalchemy to integrate application transaction management and DB session management. This approach is even recommended as one of many options by SQLAlchemy docs. Docs of zope.sqlalchemy are a bit confusing at least to me. The topic as a whole is a constant source of confusion to people starting with pyramid and thread-local sessions using SQLAlchemy.

To see a full-featured pyramid app that makes use of these packages look at ToDoPyramid - one of the sample application listed on pyramid docs pages

I cloned the project to make the database-related code at least more testable and readable to me. I found the concepts work very well - if the environment targetting the database is setup up properly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top