Performance: After_request hooks
This affects the response time after the main request processing, impacting how quickly the server sends the final response to the client.
from flask import Flask app = Flask(__name__) @app.after_request def add_header(response): response.headers['X-Fast-Header'] = 'fast' return response
from flask import Flask, request app = Flask(__name__) @app.after_request def add_header(response): import time time.sleep(1) # Simulate slow operation response.headers['X-Slow-Header'] = 'slow' return response
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy processing in after_request hook | 0 (server-side) | 0 (client-side) | 0 (client-side) | [X] Bad - delays response start |
| Lightweight header modification in after_request hook | 0 (server-side) | 0 (client-side) | 0 (client-side) | [OK] Good - fast response |
after_request hook in Flask?after_request hook in Flask?@app.after_request to register a function that modifies the response.from flask import Flask, Response
app = Flask(__name__)
@app.after_request
def add_header(response):
response.headers['X-Custom'] = 'Hello'
return response
@app.route('/')
def index():
return Response('OK')from flask import Flask
app = Flask(__name__)
@app.after_request
def fix_response():
print('Fixing response')
return 'Fixed'X-Frame-Options: DENY to all responses except those from the /public route. How can you implement this using after_request hooks?request.path, you can conditionally add headers only when the path is not '/public'.request.path != '/public'.request.path and add header only if path is not '/public' -> Option BPass the test and this pattern moves unknown