Burger King Burger King - 3 months ago 25
Python Question

Show the SQL generated by Flask-SQLAlchemy

I want to get the SQL issued by Flask-SQLAlchemy queries. In Django, I can print the

query
attribute to get SQL. How can I get something similar in Flask?

# django
>>> queryset = MyModel.objects.all()
>>> print queryset.query
SELECT "myapp_mymodel"."id", ... FROM "myapp_mymodel"

Answer

Flask-SQLAlchemy records debugging information about all queries during a request. You can get the information with get_debug_queries(). Flask-Debugtoolbar, for example, uses this to offer a debug panel with query timing information on each page render.

>>> from my_app import User
>>> from flask_sqlalchemy import get_debug_queries
>>> User.query.filter_by(display_name='davidism').all()
>>> info = get_debug_queries()[0]
>>> print(info.statement, info.parameters, info.duration, sep='\n')
SELECT "user".id AS user_id, se_user.id AS se_user_id, se_user.display_name AS se_user_display_name, se_user.profile_image AS se_user_profile_image, se_user.profile_link AS se_user_profile_link, se_user.reputation AS se_user_reputation, "user".superuser AS user_superuser \nFROM se_user JOIN "user" ON se_user.id = "user".id \nWHERE se_user.display_name = %(display_name_1)s
{'display_name_1': 'davidism'}
0.0016849040985107422

Queries are recorded if SQLALCHEMY_RECORD_QUERIES is set to True. This should be disabled when not needed for performance reasons.


Just calling str(query) does not show exactly what is sent to the database, as the final render is up to the lower-level database driver. SQLAlchemy has only the parameterized string and unescaped parameters. See the SQLAlchemy docs for a very detailed explanation of why. Usually it's good enough, but it's good to be aware that it's not the final query.