librelist archives

« back to archive

Flask-SQLAlchemy query debug helper

Flask-SQLAlchemy query debug helper

From:
Raphael Slinckx
Date:
2010-10-14 @ 21:34
Hi !

Here's another piece of code, which really should belong in
Flask-SQLAlchemy somewhere but I'm not sure how:
http://gist.github.com/627092

The idea is to store every query made by a request, and expose some
useful infos under a special url.

app = Flask(__name__)
sadebug = SaDebug()
db = SQLAlchemy()
db.init_app(app)
sadebug.init_app(app, db)

Then, somewhere in your template:
	
<% for q in get_debug_queries() %>
<a href="${q.href}">
    ${q.statement[:100]}[...]${q.statement[-100:]}
   || ${q.parameters|pprint}
   || ${'%d'|format(q.duration*1000)}ms
</a>
<% endfor %>

This will list all queries made during the request, with a link like
/__db/xxxxxxxxxxx.
If you click on that link, a new page is opened with the
syntax-highlighted and formatted sql query, the result of execution
(if it's a select), and the explain analyze of the query, plus the
time it took to perform.

It should work with sqlite and postgres at the moment, and uses
pygments for highlighting and sqlparse for formatting.

It will also print in the log a similar text-based report for each
query, with a link the the full-view to inspect for example ajax
requests where you can't output the links directly.

It would be nice to be able to add some of this stuff to
flask-sqlalchemy itself if it's considered useful, otherwise i can
release a separate package (names are welcome!).

Any thoughts?

Raf