Skip to content

Instantly share code, notes, and snippets.

@dhrrgn
Last active January 28, 2024 21:25
Show Gist options
  • Star 36 You must be signed in to star a gist
  • Fork 16 You must be signed in to fork a gist
  • Save dhrrgn/6022858 to your computer and use it in GitHub Desktop.
Save dhrrgn/6022858 to your computer and use it in GitHub Desktop.
A handy SQL debug function for Flask-SQLAlchemy
from . import app
from flask.ext.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
@jmnyarega
Copy link

awesome stuff

@ahsanulhadi
Copy link

Thanks a lot :)

@ahsanulhadi
Copy link

Update:
flask.ext.sqlalchemy - is deprecated. So using:

from flask_sqlalchemy import get_debug_queries

@pattoM
Copy link

pattoM commented Jun 28, 2018

Please revise for python 3 and above

@debashisdeb
Copy link

@andresetevejob
Copy link

thanks

@joemalski
Copy link

This is really awesome! THANKS!!!

@zihengCat
Copy link

Awesome! Thank a lot!

@alirezashojaei
Copy link

alirezashojaei commented Jan 13, 2022

Thank you for that useful function

I just added an if statement for myself to prevent useless prints

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