Profiling helps you see which parts of your Flask app take the most time. This lets you make your app faster and better.
Profiling Flask applications
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.
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()
./prof folder and simulates a slow route.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()
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.
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)
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.
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.