0
0
Flaskframework~5 mins

Response headers in Flask

Choose your learning style9 modes available
Introduction

Response headers send extra information from the server to the browser. They help control how the browser handles the response.

When you want to tell the browser the type of content it received, like JSON or HTML.
When you want to control caching so the browser knows when to save or refresh data.
When you want to add security rules, like telling the browser to only allow secure connections.
When you want to set cookies or control how cookies behave.
When you want to customize how the browser treats the response, like forcing a file download.
Syntax
Flask
from flask import Flask, Response

app = Flask(__name__)

@app.route('/')
def index():
    response = Response('Hello, world!')
    response.headers['Content-Type'] = 'text/plain'
    response.headers['X-Custom-Header'] = 'MyValue'
    return response

You create a Response object or use the one Flask gives you.

Headers are key-value pairs you add to the response.headers dictionary.

Examples
This sets the content type to JSON so the browser knows to expect JSON data.
Flask
response.headers['Content-Type'] = 'application/json'
This tells the browser not to save the response in its cache.
Flask
response.headers['Cache-Control'] = 'no-cache'
This adds a cookie to the response with extra security flags.
Flask
response.headers.add('Set-Cookie', 'user=123; HttpOnly')
This forces the browser to download the response as a file named file.txt.
Flask
response.headers['Content-Disposition'] = 'attachment; filename="file.txt"'
Sample Program

This Flask app returns a plain text message with custom headers. It tells the browser the content is plain text, adds a custom header, and disables caching.

Flask
from flask import Flask, Response

app = Flask(__name__)

@app.route('/')
def index():
    response = Response('Welcome to my site!')
    response.headers['Content-Type'] = 'text/plain'
    response.headers['X-Powered-By'] = 'Flask'
    response.headers['Cache-Control'] = 'no-store'
    return response

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Headers names are case-insensitive but usually written in Title-Case.

Some headers like Content-Type are important for browsers to understand the response.

Be careful not to overwrite important default headers unless you know why.

Summary

Response headers send extra info from server to browser.

They control content type, caching, security, and more.

In Flask, add headers by setting keys on response.headers dictionary.