Skip to Content
Flask Web Development, 2nd Edition
book

Flask Web Development, 2nd Edition

by Miguel Grinberg
March 2018
Intermediate to advanced
312 pages
7h 22m
English
O'Reilly Media, Inc.
Book available
Content preview from Flask Web Development, 2nd Edition

Chapter 16. Performance

Nobody likes slow applications. Long waits for pages to load frustrate users, so it is important to detect and correct performance problems as soon as they appear. In this chapter, two important performance aspects of web applications are considered.

Logging Slow Database Performance

When application performance slowly degenerates with time, it is likely due to slow database queries, which get worse as the size of the database grows. Optimizing database queries can be as simple as adding more indexes or as complex as adding a cache between the application and the database. The explain statement, available in most database query languages, shows the steps the database takes to execute a given query, often exposing inefficiencies in database or index design.

But before starting to optimize queries, it is necessary to determine which queries are the ones that are worth optimizing. During a typical request several database queries may be issued, so it is often hard to identify which of all the queries are the slow ones. Flask-SQLAlchemy has an option to record statistics about database queries issued during a request. In Example 16-1 you can see how this feature can be used to log queries that are slower than a configured threshold.

Example 16-1. app/main/views.py: reporting slow database queries
from flask_sqlalchemy import get_debug_queries

@main.after_app_request
def after_request(response):
    for query in get_debug_queries():
        if query.duration >= current_app ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering Flask Web Development - Second Edition

Mastering Flask Web Development - Second Edition

Daniel Gaspar, Jack Stouffer

Publisher Resources

ISBN: 9781491991725Errata Page