A response object in Flask is what your web app sends back to the user's browser. It tells the browser what to show or do next.
0
0
Response object creation in Flask
Introduction
When you want to send a simple message or HTML page back to the user.
When you need to send a file or image as a response.
When you want to customize the status code or headers of the response.
When you want to redirect the user to another page.
When you want to return JSON data from an API endpoint.
Syntax
Flask
from flask import Response response = Response(response=None, status=None, headers=None, mimetype=None, content_type=None, direct_passthrough=False)
The response parameter is the content you want to send back, like text or HTML.
You can set status to a number like 200 (OK) or 404 (Not Found).
Examples
This creates a plain text response with the message "Hello, world!" and status code 200.
Flask
from flask import Response resp = Response("Hello, world!", status=200, mimetype='text/plain')
This sends back HTML content to show a heading.
Flask
from flask import Response resp = Response("<h1>Welcome</h1>", mimetype='text/html')
This adds a custom header to the response.
Flask
from flask import Response headers = {'X-Custom-Header': 'MyValue'} resp = Response("Data", headers=headers)
This creates a response with no content but a 404 Not Found status.
Flask
from flask import Response resp = Response(status=404)
Sample Program
This Flask app sends a simple HTML heading as a response when you visit the home page.
Flask
from flask import Flask, Response app = Flask(__name__) @app.route('/') def home(): content = "<h1>Hello from Flask!</h1>" return Response(content, status=200, mimetype='text/html') if __name__ == '__main__': app.run(debug=True)
OutputSuccess
Important Notes
Use mimetype or content_type to tell the browser what kind of content you are sending.
Always set the correct status code to help browsers and tools understand the response.
Flask also provides shortcut functions like flask.jsonify and flask.redirect for common response types.
Summary
A Response object is what Flask sends back to the user's browser.
You can customize the content, status code, headers, and content type.
Creating a Response object lets you control exactly what the user receives.