I'd like to run some tests against my app to make sure I'm properly closing
all of the sessions that I open. Is there a way to get the number of open
database sessions with SQLAlchemy? Is this a strange request that hints I
may be taking the wrong approach?
Currently I'm using scoped sessions with SQLAlchemy 0.8 like so:
self.db = create_engine(connection_string)
self.Session = scoped_session(sessionmaker(bind=self.db))
# then a bunch of calls like
session = self.Session()
# ...execute queries
self.Session.remove()
I tried inspecting the engine and engine.pool objects, but neither of them
seem to have anything that stores or returns a session count. I also read
about event listening[1], but it doesn't look like the SessionMaker class
has events to hook into for opening or closing sessions.
I realize that scoped sessions return a thread-local object, so just
incrementing and decrementing a counter for each session call won't work.
But we could track the session objects in a dictionary to avoid
double-counting.
Here's what I came up with:
open_sessions = {}
def open_session(self):
session = self.Session()
self.open_sessions[session] = True
return session
def close_session(self):
session = self.Session()
self.Session.remove()
if session in self.open_sessions:
del self.open_sessions[session]
Is this the right approach?
---
[1] http://docs.sqlalchemy.org/en/rel_0_8/core/event.html
--
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/groups/opt_out.