Response
The response object that is used by default in Flask. Works like the response object from Werkzeug but is set to have an HTML mimetype by default. Quite often you don’t have to create this object yourself because Flask.make_response() will take care of that for you.
If you want to replace the response object used you can subclass this and set Flask.response_class to your subclass.
Changed in 1.0: JSON support is added to the response, like the request. This is useful when testing to get the test client response data as JSON.
Changed in 1.0: Added max_cookie_size.
Class Attributes
default_mimetype
The default mimetype for responses.
- Type:
str | None
- Default:
"text/html"
Whether to automatically correct the location header.
- Type:
bool
- Default:
False
Properties
max_cookie_size
response.max_cookie_size -> int
Read-only view of the MAX_COOKIE_SIZE config key.
See werkzeug.wrappers.Response.max_cookie_size in Werkzeug’s docs for more details.
Common Response Attributes (from Werkzeug)
The Flask Response object inherits from Werkzeug’s Response class and provides access to the following common attributes and methods:
Response Data
status_code
The HTTP status code as an integer.
from flask import Response
response = Response('Not Found', status=404)
print(response.status_code) # 404
status
The HTTP status code and reason phrase.
response = Response('Created', status=201)
print(response.status) # '201 CREATED'
data
The response body as bytes.
response = Response('Hello, World!')
print(response.data) # b'Hello, World!'
The response headers.
response = Response('Hello')
response.headers['X-Custom-Header'] = 'value'
response.headers['Content-Type'] = 'text/plain'
Methods
set_cookie()
response.set_cookie(
key: str,
value: str = '',
max_age: int | None = None,
expires: int | float | datetime | None = None,
path: str | None = '/',
domain: str | None = None,
secure: bool = False,
httponly: bool = False,
samesite: str | None = None,
partitioned: bool = False
) -> None
Sets a cookie.
The lifetime of the cookie in seconds, or None for a session cookie
expires
int | float | datetime | None
default:"None"
The expiration date/time for the cookie
The path for which the cookie is valid
The domain for which the cookie is valid
Whether the cookie should only be sent over HTTPS
Whether the cookie should be inaccessible to JavaScript
SameSite attribute (‘Lax’, ‘Strict’, or ‘None’)
Whether the cookie should be partitioned (CHIPS)
from flask import Response
response = Response('Hello')
response.set_cookie('session_id', 'abc123', max_age=3600, httponly=True)
response.set_cookie('user_pref', 'dark_mode', path='/settings')
delete_cookie()
response.delete_cookie(
key: str,
path: str = '/',
domain: str | None = None,
secure: bool = False,
httponly: bool = False,
samesite: str | None = None,
partitioned: bool = False
) -> None
Deletes a cookie by setting its expiration date in the past.
The name of the cookie to delete
The path for which the cookie was valid
The domain for which the cookie was valid
Whether the cookie was only sent over HTTPS
Whether the cookie was inaccessible to JavaScript
SameSite attribute (‘Lax’, ‘Strict’, or ‘None’)
Whether the cookie was partitioned
response = Response('Logged out')
response.delete_cookie('session_id')
set_data()
response.set_data(value: bytes | str) -> None
Sets the response body data.
response = Response()
response.set_data('Hello, World!')
get_json()
response.get_json(
force: bool = False,
silent: bool = False
) -> Any | None
Parse the response data as JSON. Useful in testing.
Ignore the mimetype and always try to parse JSON
Return None instead of raising an error on parse failure
# In tests
response = client.get('/api/users')
data = response.get_json()
assert data['username'] == 'alice'
Creating Responses
Flask provides several ways to create responses:
Return from View Function
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
# String response (200 OK by default)
return 'Hello, World!'
@app.route('/created')
def created():
# With status code
return 'Resource created', 201
@app.route('/custom-headers')
def custom_headers():
# With status code and headers
return 'OK', 200, {'X-Custom': 'value'}
Using make_response()
from flask import make_response
@app.route('/cookie')
def set_cookie():
response = make_response('Cookie set')
response.set_cookie('username', 'alice')
return response
Direct Response Object
from flask import Response
@app.route('/raw')
def raw_response():
return Response(
'Custom response',
status=200,
headers={'X-Custom': 'value'},
mimetype='text/plain'
)
JSON Responses
from flask import jsonify
@app.route('/api/user')
def get_user():
# jsonify creates a Response with application/json mimetype
return jsonify({
'id': 123,
'username': 'alice',
'email': '[email protected]'
})
Streaming Responses
from flask import Response
@app.route('/stream')
def stream():
def generate():
for i in range(10):
yield f"Line {i}\n"
return Response(generate(), mimetype='text/plain')
Example Usage
from flask import Flask, Response, make_response, jsonify
from datetime import datetime, timedelta
app = Flask(__name__)
@app.route('/download')
def download():
response = Response(
'File content here',
mimetype='application/octet-stream'
)
response.headers['Content-Disposition'] = 'attachment; filename=file.txt'
return response
@app.route('/login', methods=['POST'])
def login():
# Authenticate user...
response = make_response(jsonify({'status': 'logged in'}))
# Set secure session cookie
response.set_cookie(
'session_id',
'secure-token-here',
max_age=3600,
httponly=True,
secure=True,
samesite='Lax'
)
return response
@app.route('/logout')
def logout():
response = make_response('Logged out')
response.delete_cookie('session_id')
return response
@app.route('/api/data')
def api_data():
response = jsonify({
'users': ['alice', 'bob'],
'count': 2
})
# Add custom headers
response.headers['X-Total-Count'] = '2'
response.headers['Cache-Control'] = 'no-cache'
return response
@app.route('/redirect-temp')
def redirect_temp():
response = Response('', status=302)
response.headers['Location'] = '/new-location'
return response