0
0
Flaskframework~30 mins

Setting and reading cookies in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Setting and reading cookies in Flask
📖 Scenario: You are building a simple web app that remembers a visitor's favorite color using cookies.This helps the site greet them with their chosen color every time they visit.
🎯 Goal: Create a Flask app that sets a cookie named favorite_color when the user visits the /set_color route with a color query parameter.Then, read that cookie on the /show_color route and display a message with the stored color.
📋 What You'll Learn
Create a Flask app with two routes: /set_color and /show_color
In /set_color, set a cookie named favorite_color with the color from the query parameter
In /show_color, read the favorite_color cookie and display it in the response
Use Flask's make_response to set cookies
Handle the case where the cookie is not set by showing a default message
💡 Why This Matters
🌍 Real World
Websites often use cookies to remember user preferences like themes, languages, or login sessions to improve user experience.
💼 Career
Understanding how to set and read cookies is essential for backend web developers to manage user sessions and preferences securely.
Progress0 / 4 steps
1
Create the Flask app and import modules
Write code to import Flask, request, and make_response from flask. Then create a Flask app instance called app.
Flask
Need a hint?

Use from flask import Flask, request, make_response and then app = Flask(__name__).

2
Create the /set_color route to set the cookie
Define a route /set_color using @app.route. Inside the function set_color(), get the query parameter color from request.args. Use make_response to create a response with the text "Color set to {color}". Then set a cookie named favorite_color with the value of color on the response. Return the response.
Flask
Need a hint?

Use request.args.get('color') to get the color. Use make_response to create the response and response.set_cookie to set the cookie.

3
Create the /show_color route to read the cookie
Define a route /show_color using @app.route. Inside the function show_color(), read the cookie named favorite_color from request.cookies. If the cookie exists, return the text "Your favorite color is {color}". Otherwise, return "No favorite color set."
Flask
Need a hint?

Use request.cookies.get('favorite_color') to read the cookie. Use an if-else to return the correct message.

4
Add the app run block
Add the standard Flask app run block: if __name__ == '__main__': and inside it call app.run(debug=true).
Flask
Need a hint?

Use the standard Flask run block with debug=true for easier testing.