python SQLAlchemy 查询慢sql
1.config文件添加如下配置
FLASKY_DB_QUERY_TIMEOUT = 0.1 # 设置sql执行超时时间 0.1s SQLALCHEMY_RECORD_QUERIES = True # 启用慢查询记录功能
2.public文件添加如下代码,可将 打印的语句个性化输出
from flask_sqlalchemy import SQLAlchemy,get_debug_queries @app.after_request def after_request(response): for query in get_debug_queries(): print(query.statement,query.duration) if query.duration >= app.config['FLASKY_DB_QUERY_TIMEOUT']: # query.statement:查询的sql # query.duration: 耗时 # 打印超时sql和时间 print('----慢sql-----\t\nsql:\t\n {sql} \t\n耗时:{duration}'.format(sql=query.statement,duration=query.duration)) return response
3、完整的 public文件代码如下:
from flask import Flask from flask_sqlalchemy import SQLAlchemy,get_debug_queries import config app = Flask(__name__) app.config.from_object(config) db = SQLAlchemy(app) @app.after_request def after_request(response): for query in get_debug_queries(): if query.duration >= app.config['FLASKY_DB_QUERY_TIMEOUT']: # query.statement:查询的sql # query.duration: 耗时 # 打印超时sql和时间 print('----慢sql-----\t\nsql:\t\n {sql} \n\t耗时:{duration}'.format(sql=query.statement,duration=query.duration) return response