python SQLAlchemy 查询慢sql

参考博客: https://www.cnblogs.com/1a2a/p/10408516.html

 

1.config文件添加如下配置

1 FLASKY_DB_QUERY_TIMEOUT = 0.1  # 设置sql执行超时时间 0.1s
2 SQLALCHEMY_RECORD_QUERIES = True  # 启用慢查询记录功能

 

2.public文件添加如下代码,可将 打印的语句个性化输出

 1 from flask_sqlalchemy get_debug_queries
 2 
 3 @app.after_request
 4 def after_request(response):
 5     for query in get_debug_queries():
 6         if query.duration >= app.config['FLASKY_DB_QUERY_TIMEOUT']:
 7              # query.statement:查询的sql
 8              # query.duration: 耗时 
 9              # 打印超时sql和时间
10              print('----慢sql-----\t\nsql:\t\n {sql} \t\n耗时:{duration}'.format(sql=query.statement,duration=query.duration)
11     return response

完整的 public文件代码如下:

 1 from flask import Flask
 2 from flask_sqlalchemy import SQLAlchemy,get_debug_queries
 3 import config
 4 
 5 app = Flask(__name__)
 6 app.config.from_object(config)
 7 db = SQLAlchemy(app)
 8 
 9 @app.after_request
10 def after_request(response):
11     for query in get_debug_queries():
12         if query.duration >= app.config['FLASKY_DB_QUERY_TIMEOUT']:
13             # query.statement:查询的sql
14             # query.duration: 耗时 
15             # 打印超时sql和时间
16             print('----慢sql-----\t\nsql:\t\n {sql} \n\t耗时:{duration}'.format(sql=query.statement,duration=query.duration)
17     return response

 

 

效果如图:

 

posted @ 2020-05-05 17:34  菜小鱼~  阅读(1602)  评论(0编辑  收藏  举报