0
0
Flaskframework~30 mins

How cookies work in HTTP in Flask - Try It Yourself

Choose your learning style9 modes available
How cookies work in HTTP with Flask
📖 Scenario: You are building a simple web app using Flask. You want to remember a visitor's name using cookies so that when they come back, the app greets them personally.
🎯 Goal: Create a Flask app that sets a cookie with the visitor's name and reads it back to greet them on return visits.
📋 What You'll Learn
Create a Flask app with one route '/'
Set a cookie named 'username' with value 'Alice' when the visitor first arrives
Read the 'username' cookie on subsequent visits
Display a greeting message using the cookie value if it exists
Use Flask's make_response to set cookies
💡 Why This Matters
🌍 Real World
Cookies are used by websites to remember users, keep them logged in, and personalize their experience.
💼 Career
Understanding cookies is essential for web developers to manage user sessions and preferences securely.
Progress0 / 4 steps
1
Set up the Flask app and route
Import Flask and request from flask. Create a Flask app called app. Define a route for '/' with a function called index that returns the string 'Welcome!'.
Flask
Need a hint?

Start by importing Flask and request, then create the app and a simple route that returns a welcome message.

2
Add a variable to hold the cookie name
Create a variable called cookie_name and set it to the string 'username'.
Flask
Need a hint?

This variable will store the name of the cookie we use to remember the visitor.

3
Check for the cookie and set it if missing
In the index function, import make_response from flask. Use request.cookies.get(cookie_name) to get the cookie value and store it in username. If username is None, create a response with the text 'Hello, new visitor!' and set a cookie named cookie_name with value 'Alice'. Otherwise, create a response with the text f'Welcome back, {username}!'. Return the response.
Flask
Need a hint?

Use request.cookies.get() to read the cookie. Use make_response() to create a response and set_cookie() to add a cookie.

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

This block runs the Flask app when you start the script.