Performance: Profiling Flask applications
Profiling Flask apps affects server response time and helps identify slow code paths impacting user wait time.
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(): import time time.sleep(0.5) # simulate slow code return 'Hello World' if __name__ == '__main__': app.run()
import time from flask import Flask, request app = Flask(__name__) @app.route('/') def index(): start = time.time() # handle request time.sleep(0.5) # simulate slow code duration = time.time() - start print(f'Request took {duration}s') return 'Hello World' if __name__ == "__main__": app.run()
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual print timing | 0 | 0 | 0 | [X] Bad |
| ProfilerMiddleware usage | 0 | 0 | 0 | [OK] Good |
| Manual DB query timing | 0 | 0 | 0 | [X] Bad |
| SQLAlchemy event profiling | 0 | 0 | 0 | [OK] Good |
from flask import Flask
from werkzeug.middleware.profiler import ProfilerMiddleware
app = Flask(__name__)
app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[10])
@app.route('/')
def home():
return 'Hello Profiling!'
if __name__ == '__main__':
app.run()from flask import Flask
from werkzeug.middleware.profiler import ProfilerMiddleware
app = Flask(__name__)
app = ProfilerMiddleware(app, restrictions=[10])
@app.route('/')
def index():
return 'Test'Pass the test and this pattern moves unknown