I've been working with a handful of SQLAlchemy and Pyramid based projects recently, and two situations have repeatedly come up:
1. Given a SQLAlchemy Object, access the SQLAlchemy Session
2. Given a SQLAlchemy Object or Session, access the Pyramid Request object
The general solutions I've used to handle this is:
1. An Object can use the runtime inspection API to grab it's active session:
from sqlalchemy import inspect
@property
def _active_session(self):
dbSession = inspect(self).session
return dbSession
2. Attach the Pyramid request to the session_factory when a session is created:
def get_tm_session(request):
dbSession = session_factory()
zope.sqlalchemy.register(dbSession, transaction_manager=transaction_manager, keep_session=True)
if request is not None:
def _cleanup(request):
dbSession.close()
request.add_finished_callback(_cleanup)
# cache our request onto the dbsession
dbSession.pyramid_request = request
return dbSession
I've needed to implement these patterns in a lot of projects. This makes me wonder if there is/could be a better way.
1. Would it be beneficial if ORM objects could surface the current Session, if any, as a documented property ? I do this in my base classes, but with the overhead of the inspect system, and I repeat this in every project.
2. Would it be better for the sessionmaker had any of ?
a. An official namespace were developers could attach information. I'm using `pyramid_request` because I doubt SQLAlchemy will every step on that - but it would be nice if there were a dedicated attribute/object/namespace on the Session
b. `sqlalchemy.orm.session.Session()` could accept a dict/payload/object/whatever on init, which would be attached to a single session in the aforementioned dedicated namespace.
The usage would be something like:
sess = Session(customized={"request": request})
which might then me accessed as:
sess.customized.request