Flask by Example: Response Header Configuration
Setting HTTP headers is vital for security, caching, and content negotiation. This demonstrates how to add headers to responses globally using `after_request` hooks.
Code
from flask import Flask, make_response
app = Flask(__name__)
# 1. Global Header Injection
# This runs after EVERY request, before sending to client
@app.after_request
def add_security_headers(response):
# Prevent clickjacking
response.headers['X-Frame-Options'] = 'SAMEORIGIN'
# Enforce HTTPS (HSTS)
response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
# Prevent MIME type sniffing
response.headers['X-Content-Type-Options'] = 'nosniff'
return response
@app.route('/cache')
def cached_data():
resp = make_response("This data is cacheable")
# 2. Caching Headers
# Cache for 60 seconds
resp.headers['Cache-Control'] = 'public, max-age=60'
return resp
@app.route('/download')
def download_file():
csv_data = "col1,col2\nval1,val2"
resp = make_response(csv_data)
# 3. Content-Disposition
# Forces the browser to download as a file named 'data.csv'
resp.headers['Content-Disposition'] = 'attachment; filename=data.csv'
resp.headers['Content-Type'] = 'text/csv'
return respExplanation
Using the @app.after_request decorator allows you to apply headers globally to all responses generated by your application. This is particularly useful for enforcing site-wide policies without repeating code in every view function.
This approach is ideal for security policies like Strict-Transport-Security (HSTS) and X-Content-Type-Options. By applying them globally, you ensure that no route is accidentally left unprotected, significantly hardening your application's security posture.
For specific routes, you can still manually set headers on the response object. A common use case is setting Content-Disposition, which tells the browser to treat the response as a file download rather than displaying it inline.
Code Breakdown
@app.after_request registers a function to run after the view function returns but before the response is sent to the network. It receives the response object and must return it (modified or not).X-Frame-Options: SAMEORIGIN prevents other sites from embedding your site in an iframe. This is a standard defense against Clickjacking attacks.Cache-Control tells browsers and proxies how long they can keep a copy of this response. max-age=60 means the browser won't ask the server for this data again for 1 minute.Content-Disposition: attachment triggers the "Save As" dialog in the browser. Without this, the browser might try to display the CSV text directly in the window.
