Skip to content

Instantly share code, notes, and snippets.

@joemalski
Last active June 8, 2020 23:36
Show Gist options
  • Save joemalski/1e8fa236a8b513f76f9207480d5e48a6 to your computer and use it in GitHub Desktop.
Save joemalski/1e8fa236a8b513f76f9207480d5e48a6 to your computer and use it in GitHub Desktop.
Flask SqlAlchemy Debugger
'''
Flask SqlAlchemy Debugger (Python 3)
------------------------------------
Shows the actual "sql query equivalent" of Flask-SQLAlchemy for debugging purposes
and gives you a rough estimation of where in your application query was issued.
Only runs when you enable "FLASK_ENV=development", since this will automatically set the
"FLASK_DEBUG=1" or explicitly set "FLASK_DEBUG=1". If you are in "FLASK_ENV=testing" (testing mode)
or "FLASK_ENV=production" and you want to make it work without enabling the debugging mode,
set "SQLALCHEMY_RECORD_QUERIES=True" in your flask configuration.
How to use it?
--------------
You can add this function to your "routes.py" file, using the decorator "@app.after_request"
or using this variant "app.after_request(sql_debug)".
I got the inspiration from dhrrgn, but decided to create my own.
https://gist.github.com/dhrrgn/6022858
'''
from flask_sqlalchemy import get_debug_queries
@app.after_request
def sql_debug(response):
queries = list(get_debug_queries())
if len(queries):
print('=' * 80)
print(' FLASK SQLALCHEMY, DEBUG SQL QUERIES:')
print('=' * 80)
print()
total_duration = 0.0
for i, q in enumerate(queries):
total_duration += q.duration
print(" Query({}): {}".format(i+1, q.statement))
if q.parameters:
l = len(str(i+1))+11
print('{}{}'.format(' '*l, q.parameters))
print(" Context: {}".format(q.context))
print(" Duration: {}".format(round(q.duration*1000,2)))
print()
print('=' * 80)
print(' Total SQL Queries:', len(queries))
print(" Total Query Duration: {} ms".format(
round(total_duration*1000,2)))
print('=' * 80)
print()
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment