From 189b16d849f1eca36a08fb5f3482fd15d0f7fbca Mon Sep 17 00:00:00 2001 From: Miguel Grinberg Date: Tue, 18 Jul 2017 07:55:50 -0700 Subject: [PATCH] Chapter 16: Logging of slow database queries (16a) --- app/main/views.py | 12 ++++++++++++ config.py | 2 ++ 2 files changed, 14 insertions(+) diff --git a/app/main/views.py b/app/main/views.py index 68acd9c49..5b30b245c 100644 --- a/app/main/views.py +++ b/app/main/views.py @@ -1,6 +1,7 @@ from flask import render_template, redirect, url_for, abort, flash, request,\ current_app, make_response from flask_login import login_required, current_user +from flask_sqlalchemy import get_debug_queries from . import main from .forms import EditProfileForm, EditProfileAdminForm, PostForm,\ CommentForm @@ -9,6 +10,17 @@ from ..decorators import admin_required, permission_required +@main.after_app_request +def after_request(response): + for query in get_debug_queries(): + if query.duration >= current_app.config['FLASKY_SLOW_DB_QUERY_TIME']: + current_app.logger.warning( + 'Slow query: %s\nParameters: %s\nDuration: %fs\nContext: %s\n' + % (query.statement, query.parameters, query.duration, + query.context)) + return response + + @main.route('/shutdown') def server_shutdown(): if not current_app.testing: diff --git a/config.py b/config.py index 446b0d408..4c8bf6b56 100644 --- a/config.py +++ b/config.py @@ -14,9 +14,11 @@ class Config: FLASKY_MAIL_SENDER = 'Flasky Admin ' FLASKY_ADMIN = os.environ.get('FLASKY_ADMIN') SQLALCHEMY_TRACK_MODIFICATIONS = False + SQLALCHEMY_RECORD_QUERIES = True FLASKY_POSTS_PER_PAGE = 20 FLASKY_FOLLOWERS_PER_PAGE = 50 FLASKY_COMMENTS_PER_PAGE = 30 + FLASKY_SLOW_DB_QUERY_TIME = 0.5 @staticmethod def init_app(app):