简体   繁体   English

显示Flask-SQLAlchemy生成的SQL

[英]Show the SQL generated by Flask-SQLAlchemy

I want to get the SQL issued by Flask-SQLAlchemy queries. 我想获取Flask-SQLAlchemy查询发出的SQL。 In Django, I can print the query attribute to get SQL. 在Django中,我可以打印query属性以获取SQL。 How can I get something similar in Flask? 我如何在Flask中获得类似的东西?

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

Flask-SQLAlchemy records debugging information about all queries during a request. Flask-SQLAlchemy记录有关请求期间所有查询的调试信息。 You can get the information with get_debug_queries() . 您可以使用get_debug_queries()获取信息。 Flask-Debugtoolbar , for example, uses this to offer a debug panel with query timing information on each page render. 例如, Flask-Debugtoolbar使用此工具为调试面板提供每个页面渲染中的查询时间信息。

get_debug_queries() returns a list of queries in the order they were performed. get_debug_queries()以查询的执行顺序返回查询列表。

>>> 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 . 如果SQLALCHEMY_RECORD_QUERIES设置为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. 仅调用str(query)并不能确切显示发送到数据库的内容,因为最终的呈现取决于较低级别的数据库驱动程序。 SQLAlchemy has only the parameterized string and unescaped parameters. SQLAlchemy仅具有参数化的字符串和未转义的参数。 See the SQLAlchemy docs for a very detailed explanation of why. 有关原因的详细说明,请参见SQLAlchemy文档 Usually it's good enough, but it's good to be aware that it's not the final query. 通常,它足够好,但是要知道这不是最终查询,这很高兴。

I have found answer. 我找到答案了。 I just invoke str and then get the sql. 我只是调用str ,然后获取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'

To print the generated SQL for all the queries, set the configuration SQLALCHEMY_ECHO=True . 要为所有查询打印生成的SQL,请设置配置SQLALCHEMY_ECHO=True

app.config['SQLALCHEMY_ECHO'] = True

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM