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.
Flask accepts several return types from route handler functions:
200 OK, Content-Type: text/html).200 OK, Content-Type: application/json).(body, status): Sets custom status code: return {"error": "Not Found"}, 404.(body, status, headers): Sets status code and custom HTTP headers.flask.Response or created via make_response().make_response() for Explicit ControlWhen you need to mutate response headers, set cookies, or manipulate binary data before transmission, wrap the content in make_response():
Cookies are small text strings stored by the client browser and transmitted in the Cookie header on subsequent requests.
response.set_cookie())Cookies must be attached to an outgoing response object before returning:
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.request.cookies)response.delete_cookie())Deleting a cookie sets its expiration date to the past:
Response object?httponly=True?secure=True cookie attribute guarantee?make_response()?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| The Flask Request Object & Data Parsing | Reverse Routing with url_for, Aborts & Error Handlers |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.