Created
March 21, 2017 17:35
-
-
Save luhn/96cd88fe69e65b75166d07e6a6f42923 to your computer and use it in GitHub Desktop.
SQLAlchemy query counter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sqlalchemy import engine_from_config, event | |
from sqlalchemy.orm import sessionmaker | |
def query_count_hook( | |
conn, cursor, statement, parameters, context, executemany, | |
): | |
info = conn.info | |
info['query_count'] = info.get('query_count', 0) + 1 | |
engine = engine_from_config(settings, prefix='sqlalchemy.') | |
dbmaker = sessionmaker(bind=engine) | |
event.listen(engine, 'after_cursor_execute', query_count_hook) | |
def session(request): | |
""" | |
Create SQLAlchemy session for each web request. | |
""" | |
session = dbmaker() | |
def cleanup(request): | |
""" | |
Destroy session after web request. | |
""" | |
conn_info = session.connection().info | |
print(conn_info.get('query_count', 0)) | |
conn_info['query_count'] = 0 | |
if request.exception is not None: | |
session.rollback() | |
else: | |
session.commit() | |
session.close() | |
request.add_finished_callback(cleanup) | |
return session |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment