Performance: Secure headers configuration
This affects page load speed by adding HTTP headers that can slightly delay the initial response but improve security and user trust.
from flask import Flask from flask_talisman import Talisman app = Flask(__name__) # Use Flask-Talisman to set secure headers globally Talisman(app, content_security_policy="default-src 'self'", frame_options='DENY') @app.route('/') def index(): return 'Hello World'
from flask import Flask, make_response app = Flask(__name__) @app.route('/') def index(): response = make_response('Hello World') # Adding headers manually each time response.headers['X-Frame-Options'] = 'DENY' response.headers['Content-Security-Policy'] = "default-src 'self'" return response
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual header setting per route | 0 | 0 | 0 | [OK] |
| Global header setting via middleware (Flask-Talisman) | 0 | 0 | 0 | [OK] Good |
@app.after_request.@app.after_request.@app.after_request decorator -> Option C@app.after_request to add headers [OK]@app.after_request for all responses [OK]@app.route which only defines routes@app.before_first_request which runs once@app.teardown_request which is for cleanup, not response modificationresponse.headers.response.headers['Header-Name'] = value to set or overwrite headers.response.headers [OK]response.headers['Name'] = value to set headers [OK]header instead of headersset_header which Flask response lacksheaders.add which is not a Flask methodX-Frame-Options header in the response?from flask import Flask, Response
app = Flask(__name__)
@app.after_request
def add_headers(response: Response):
response.headers['X-Frame-Options'] = 'DENY'
return response
@app.route('/')
def home():
return 'Hello'@app.after_requestX-Frame-Options to 'DENY' on every response.X-Frame-Options: DENY.X-Frame-Options set to 'DENY' in after_request [OK]@app.after_request apply to all responses [OK]SAMEORIGIN with DENYfrom flask import Flask
app = Flask(__name__)
@app.after_request
def secure_headers(response):
response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
return response
@app.route('/')
def index():
return 'Welcome'@app.after_request functions take one parameter (response) and return it. This matches the code.@app.after_request [OK]@app.after_request runs after response creation and can access request.is_secure to conditionally add headers efficiently for all routes.@app.before_request cannot modify response headers.@app.after_request to check request.is_secure and add headers conditionally -> Option A@app.after_request is best [OK]request.is_secure in @app.after_request [OK]@app.before_request which can't modify responsePass the test and this pattern moves unknown