SessionExtension將是有益的檢查
例如:
import traceback
from collections import defaultdict
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
from 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):
for cnn, callers in self.connections.items():
print(cnn)
for 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()
對不起,我的英語不好(
的面貌邁向[事件API(http://docs.sqlalchemy.org /en/rel_0_8/core/event.html)爲攔截事物的現代系統。 – zzzeek 2013-05-16 04:10:30