I have a number of classes that are mapped to tables with SQLAlchemy (non-declaratively if that matters). Because I'd like the application to be unit-testable, all SQLAlchemy session interaction is isolated into a single class. Using the app goes something like this:
m = Model("mysql://localhost/mydb")
s1 = Service("somename")
m.session.add(s1)
s1 is m.get_service("somename") # True
It's actually more streamlined than that, but work with me here.
Is it possible to skip the session.add() step? In other words, if I instantiate a mapped class, is it possible for that be automatically added to the active SQLAlchemy session (if any)?
In SQLAlchemy you can only do this with tables by binding their metadata to an engine. This does not work with the ORM part of SQLALchemy.
http://www.sqlalchemy.org/docs/core/schema.html?highlight=metadata#binding-metadata-to-an-engine-or-connection
One approach to this sort of thing is to use a scoped session that can be accessed anywhere.
http://www.sqlalchemy.org/docs/orm/session.html?highlight=scoped%20session#sqlalchemy.orm.scoped_session
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With