Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to add an object to SQLAlchemy session without explicit session.add()?

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)?

like image 538
sh-beta Avatar asked Nov 06 '10 23:11

sh-beta


1 Answers

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

like image 102
Nathan Villaescusa Avatar answered Sep 28 '22 16:09

Nathan Villaescusa