Show the SQL generated by Flask-SQLAlchemy

Question:

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"
Asked By: Burger King

||

Answers:

I have found answer. I just invoke str and then get the sql.

>>> str(User.query.filter_by(role_id=user_role))
'SELECT users.id AS users_id, users.username AS users_username, users.role_id AS
 users_role_id nFROM users nWHERE users.role_id = :role_id_1'
Answered By: Burger King

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.

get_debug_queries() returns a list of queries in the order they were performed.

>>> 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.

Answered By: davidism

To print the generated SQL for all the queries, set the configuration SQLALCHEMY_ECHO=True.

app.config['SQLALCHEMY_ECHO'] = True

http://flask-sqlalchemy.pocoo.org/2.3/config/

Answered By: Bless
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.