Skip to content

Commit 97446ad

Browse files
Chapter 16: Logging of slow database queries (16a)
1 parent 1827acd commit 97446ad

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

app/main/views.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from flask import render_template, redirect, url_for, abort, flash, request,\
22
current_app, make_response
33
from flask_login import login_required, current_user
4+
from flask_sqlalchemy import get_debug_queries
45
from . import main
56
from .forms import EditProfileForm, EditProfileAdminForm, PostForm,\
67
CommentForm
@@ -9,6 +10,17 @@
910
from ..decorators import admin_required, permission_required
1011

1112

13+
@main.after_app_request
14+
def after_request(response):
15+
for query in get_debug_queries():
16+
if query.duration >= current_app.config['FLASKY_SLOW_DB_QUERY_TIME']:
17+
current_app.logger.warning(
18+
'Slow query: %s\nParameters: %s\nDuration: %fs\nContext: %s\n'
19+
% (query.statement, query.parameters, query.duration,
20+
query.context))
21+
return response
22+
23+
1224
@main.route('/shutdown')
1325
def server_shutdown():
1426
if not current_app.testing:

config.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,11 @@ class Config:
1414
FLASKY_MAIL_SENDER = 'Flasky Admin <flasky@example.com>'
1515
FLASKY_ADMIN = os.environ.get('FLASKY_ADMIN')
1616
SQLALCHEMY_TRACK_MODIFICATIONS = False
17+
SQLALCHEMY_RECORD_QUERIES = True
1718
FLASKY_POSTS_PER_PAGE = 20
1819
FLASKY_FOLLOWERS_PER_PAGE = 50
1920
FLASKY_COMMENTS_PER_PAGE = 30
21+
FLASKY_SLOW_DB_QUERY_TIME = 0.5
2022

2123
@staticmethod
2224
def init_app(app):

0 commit comments

Comments
 (0)