python - How to monitor/log sqlalchemy scoped sessions? -


i working on legacy application uses sqlalchemy , architecture is...well...suboptimal.

i discovered there lot of (unneeded) mysql connections openned application, , pin down code that. suppose result of scoped_sessions left open.

i search them manually wondering if possible instrumentalise code discover bugged functions/modules. (a sqlalchemy monitor useful, don't think exists).

sessionextension usefull inspecting

for example:

import traceback collections import defaultdict sqlalchemy import create_engine sqlalchemy.orm import sessionmaker, scoped_session sqlalchemy.orm.interfaces import sessionextension   # todo cleanup commited sessions class mysessionusageinspector(sessionextension):      def __init__(self):         self.connections = defaultdict(list)      def after_begin(self, session, transaction, connection):         self.connections[connection].append(traceback.format_stack()[0])      def repr_usage(self):         cnn, callers in self.connections.items():             print(cnn)             index, caller in enumerate(callers):                 print('\t', index, caller)   if __name__ == '__main__':     engine = create_engine('sqlite://')     session_inspector = mysessionusageinspector()     session = scoped_session(sessionmaker(bind=engine,          extension=session_inspector)     )     session = session()      session.execute('select 1;')     session.commit()     session.execute('select 2;')      print('session usage:')     session_inspector.repr_usage() 

sorry poor english (


Comments

Popular posts from this blog

php - mySql Join with 4 tables -

css - Text drops down with smaller window -

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -