0
0
Flaskframework~5 mins

Profiling Flask applications

Choose your learning style9 modes available
Introduction

Profiling helps you see which parts of your Flask app take the most time. This lets you make your app faster and better.

You want to find slow parts in your Flask web app.
You need to improve the speed of a specific page or function.
You want to check how long database queries take in your app.
You are preparing your app for more users and want to optimize performance.
Syntax
Flask
from flask import Flask
from werkzeug.middleware.profiler import ProfilerMiddleware

app = Flask(__name__)

app.wsgi_app = ProfilerMiddleware(app.wsgi_app, profile_dir='./profile_data')

@app.route('/')
def home():
    return 'Hello, Flask Profiling!'

if __name__ == '__main__':
    app.run(debug=True)

The ProfilerMiddleware wraps your Flask app to collect timing data.

The profile_dir folder stores the profiling reports for later review.

Examples
This example limits the profiler output to the top 30 functions by time.
Flask
from flask import Flask
from werkzeug.middleware.profiler import ProfilerMiddleware

app = Flask(__name__)
app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30])

@app.route('/')
def index():
    return 'Profile example'

if __name__ == '__main__':
    app.run()
This example saves profiling data in the ./prof folder and simulates a slow route.
Flask
from flask import Flask
from werkzeug.middleware.profiler import ProfilerMiddleware

app = Flask(__name__)
app.wsgi_app = ProfilerMiddleware(app.wsgi_app, profile_dir='./prof')

@app.route('/slow')
def slow():
    import time
    time.sleep(1)
    return 'Slow response'

if __name__ == '__main__':
    app.run()
Sample Program

This Flask app uses ProfilerMiddleware to collect performance data. It has two routes: one simple and one that does a calculation to show some work. Profiling data will be saved in the ./profile_reports folder.

Flask
from flask import Flask
from werkzeug.middleware.profiler import ProfilerMiddleware

app = Flask(__name__)

# Wrap the app with profiler middleware
app.wsgi_app = ProfilerMiddleware(app.wsgi_app, profile_dir='./profile_reports')

@app.route('/')
def hello():
    return 'Hello, Flask Profiling!'

@app.route('/compute')
def compute():
    total = 0
    for i in range(100000):
        total += i
    return f'Computed sum: {total}'

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Profiling slows down your app a bit, so use it only during development or testing.

Check the generated profile files with tools like snakeviz or cProfile for easier reading.

Remember to remove or disable profiling in production to keep your app fast.

Summary

Profiling helps find slow parts in your Flask app.

Use ProfilerMiddleware from Werkzeug to add profiling easily.

Save and analyze profile data to improve your app's speed.