Performance: Response headers
Response headers affect how quickly the browser can start rendering and how it caches or processes the content.
from flask import Flask, Response app = Flask(__name__) @app.route('/') def index(): headers = {'Cache-Control': 'public, max-age=3600'} return Response('Hello World', headers=headers)
from flask import Flask, Response app = Flask(__name__) @app.route('/') def index(): headers = {'X-Powered-By': 'Flask', 'Server': 'MyServer', 'Cache-Control': 'no-cache', 'Extra-Header': 'unnecessary'} return Response('Hello World', headers=headers)
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Sending many unnecessary headers | 0 | 0 | Low but delays initial paint | [X] Bad |
| Sending minimal, essential headers with caching | 0 | 0 | Minimal delay, faster paint | [OK] Good |
X-Custom-Header with value Test to a Flask response?response.headers['X-Custom-Header'] = 'Test' uses the correct dictionary assignment syntax.Content-Type header in the response?from flask import Flask, make_response
app = Flask(__name__)
@app.route('/')
def index():
response = make_response('Hello')
response.headers['Content-Type'] = 'application/json'
return responseresponse.headers['Content-Type'] = 'application/json', which overrides the default.application/json.from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
response = 'Hello'
response.headers['X-Test'] = 'Value'
return responseCache-Control with value no-store to all responses in your Flask app. Which is the best way to do this?@app.after_request decorator lets you modify every response before sending it.@app.after_request decorator adds the header to every response automatically, which is efficient and clean.Pass the test and this pattern moves unknown