Response Objects, make_response & Cookies
Response Objects, make_response & Cookies
Whenever a Flask view function completes execution, its return value is converted into an HTTP response object. Understanding how Flask constructs responses—and how to customize status codes, headers, and cookies using make_response—is critical for building robust web applications.
1. What Can a Flask View Return?
Flask accepts several return types from route handler functions:
- 1A String: Converted to an HTML response (
200 OK,Content-Type: text/html). - 2A Dict or List: Automatically serialized to JSON (
200 OK,Content-Type: application/json). - 3A Tuple
(body, status): Sets custom status code:return {"error": "Not Found"}, 404. - 4A Tuple
(body, status, headers): Sets status code and custom HTTP headers. - 5A WSGI Response Object: An instance of
flask.Responseor created viamake_response().
2. Using make_response() for Explicit Control
When you need to mutate response headers, set cookies, or manipulate binary data before transmission, wrap the content in make_response():
3. Working with HTTP Cookies
Cookies are small text strings stored by the client browser and transmitted in the Cookie header on subsequent requests.
A. Setting a Cookie (response.set_cookie())
Cookies must be attached to an outgoing response object before returning:
Cookie Security Attributes:
httponly=True: Prevents client-side scripts (document.cookie) from reading the cookie, mitigating cross-site scripting (XSS) attacks.secure=True: Instructs the browser to only transmit the cookie over encrypted TLS/HTTPS connections.samesite="Lax"or"Strict": Restricts cross-site cookie transmission to mitigate CSRF attacks.
B. Reading a Cookie (request.cookies)
C. Deleting a Cookie (response.delete_cookie())
Deleting a cookie sets its expiration date to the past:
Practice Quiz
Response object?httponly=True?secure=True cookie attribute guarantee?make_response()?Reverse Routing with url_for, Aborts & Error Handlers
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| The Flask Request Object & Data Parsing | Reverse Routing with url_for, Aborts & Error Handlers |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.