Skip to content

Instantly share code, notes, and snippets.

@debashisdeb
Forked from dhrrgn/debug_stuff.py
Last active March 13, 2023 15:58
Show Gist options
  • Save debashisdeb/7d6640d8cd6d3b9fb2c51695d6cda882 to your computer and use it in GitHub Desktop.
Save debashisdeb/7d6640d8cd6d3b9fb2c51695d6cda882 to your computer and use it in GitHub Desktop.
A handy SQL debug function for Flask-SQLAlchemy
from . import app
from flask.sqlalchemy import get_debug_queries
if app.debug:
app.after_request(sql_debug)
def sql_debug(response):
queries = list(get_debug_queries())
query_str = ''
total_duration = 0.0
for q in queries:
total_duration += q.duration
stmt = str(q.statement % q.parameters).replace('\n', '\n ')
query_str += 'Query: {0}\nDuration: {1}ms\n\n'.format(stmt, round(q.duration * 1000, 2))
print('=' * 80)
print(' SQL Queries - {0} Queries Executed in {1}ms'.format(len(queries), round(total_duration * 1000, 2)))
print('=' * 80)
print(query_str.rstrip('\n'))
print('=' * 80 + '\n')
return response
@iras
Copy link

iras commented Dec 22, 2020

Thanks.

Also, I replaced

stmt = str(q.statement % q.parameters).replace('\n', '\n       ')

with

statement = str(q.statement).replace( '?', '%s' )
stmt = str( statement % q.parameters ).replace('\n', '\n       ')

@alirezashojaei
Copy link

alirezashojaei commented Jan 13, 2022

Thank you for that useful function

@Jehad-C
Copy link

Jehad-C commented Jan 30, 2023

Have you already make this functional?
I have a problem,everytime I go to roo URL nothing is incremented.
Also based on debugging, I found that there is no output list in get_debug_queries()
I already set app.config[ 'SQLALCHEMY_RECORD_QUERIES' ] = True

2023-01-30 18:30:22,460 INFO sqlalchemy.engine.Engine BEGIN (implicit)
2023-01-30 18:30:22,472 INFO sqlalchemy.engine.Engine SELECT user.id AS user_id, user.name AS user_name
FROM user
WHERE user.id = ?
LIMIT ? OFFSET ?
2023-01-30 18:30:22,472 INFO sqlalchemy.engine.Engine [generated in 0.00121s] (3, 1, 0)
2023-01-30 18:30:22,475 INFO sqlalchemy.engine.Engine ROLLBACK

SQL Queries - 0 Queries Executed in 0.0ms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment