Bird
Raised Fist0
Flaskframework~15 mins

Setting and reading cookies in Flask - Deep Dive

Choose your learning style10 modes available
Overview - Setting and reading cookies
What is it?
Cookies are small pieces of data stored by a web browser that help websites remember information about you. In Flask, you can set cookies to save data on the user's browser and read them later when the user visits again. This helps create a smoother and more personalized experience. Cookies are sent back and forth between the browser and server with each request and response.
Why it matters
Without cookies, websites would forget who you are every time you visit, making you log in repeatedly or lose your preferences. Cookies solve this by storing small bits of data on your device, allowing websites to recognize you and keep track of your session or settings. This makes web apps feel more friendly and useful.
Where it fits
Before learning cookies, you should understand how HTTP requests and responses work in Flask. After cookies, you can learn about sessions, which build on cookies to manage user login states more securely.
Mental Model
Core Idea
Cookies are like tiny notes your browser keeps for a website to remember you between visits.
Think of it like...
Imagine visiting a coffee shop where the barista writes your favorite drink on a sticky note and sticks it on your cup. Next time you come, they see the note and make your drink without asking. Cookies work similarly by storing small notes in your browser for websites.
┌───────────────┐       ┌───────────────┐
│   Browser     │       │    Server     │
│               │       │               │
│  Stores cookie│◄──────│  Sets cookie  │
│  Sends cookie │──────►│  Reads cookie │
└───────────────┘       └───────────────┘
Build-Up - 7 Steps
1
FoundationWhat are cookies in web apps
🤔
Concept: Cookies store small data on the user's browser to remember information between visits.
Cookies are pieces of text data that websites ask your browser to save. Each time you visit, your browser sends these cookies back to the website. This helps the website remember things like your language choice or login status.
Result
You understand that cookies are small data stored on your device by websites to keep track of information.
Understanding cookies as stored notes in the browser is the base for all web personalization and session management.
2
FoundationHow Flask handles HTTP requests and responses
🤔
Concept: Flask uses request and response objects to communicate with the browser, which is where cookies live.
When a user visits a Flask app, Flask creates a request object with data from the browser, including any cookies sent. Flask then sends back a response object, which can include new cookies to store. Cookies travel inside HTTP headers.
Result
You see that cookies are part of the HTTP headers in requests and responses in Flask.
Knowing that cookies are part of HTTP headers helps you understand how to read and set them in Flask's request and response objects.
3
IntermediateSetting cookies in Flask responses
🤔Before reading on: Do you think setting a cookie requires modifying the request or the response object? Commit to your answer.
Concept: Cookies are set by adding them to the response object before sending it to the browser.
In Flask, you create a response (like with make_response) and then use response.set_cookie(key, value) to add a cookie. When the browser receives this response, it saves the cookie for future requests.
Result
The browser stores the cookie you set and sends it back on later visits.
Understanding that cookies are set on the response clarifies why you can't set cookies just by reading the request.
4
IntermediateReading cookies from Flask requests
🤔Before reading on: Do you think cookies are stored in the response or request object when a user visits? Commit to your answer.
Concept: Cookies sent by the browser are available in the Flask request object under request.cookies.
When a user visits, Flask's request.cookies dictionary contains all cookies sent by the browser. You can access a cookie by its name, for example, request.cookies.get('username').
Result
You can retrieve stored cookie values sent by the browser in your Flask route handlers.
Knowing that cookies come from the request helps you understand how to personalize responses based on stored data.
5
IntermediateCookie attributes and security options
🤔Before reading on: Do you think cookies are always accessible by JavaScript or only by the server? Commit to your answer.
Concept: Cookies have attributes like expiration, path, HttpOnly, and Secure that control their behavior and security.
When setting cookies in Flask, you can specify options like max_age (how long it lasts), path (which URLs send it), HttpOnly (prevents JavaScript access), and Secure (only sent over HTTPS). These control how and when cookies are sent and protect user data.
Result
You can create cookies that expire, are limited to certain paths, or are protected from JavaScript to improve security.
Understanding cookie attributes helps you write safer web apps and avoid common security risks like cross-site scripting.
6
AdvancedDeleting and updating cookies in Flask
🤔Before reading on: Do you think deleting a cookie means removing it from the request or instructing the browser to remove it? Commit to your answer.
Concept: To delete a cookie, you send a response that tells the browser to remove it by setting its expiration in the past.
Flask's response.delete_cookie(key) method sends a cookie with the same name but an expired date, instructing the browser to remove it. Updating a cookie is done by setting it again with a new value.
Result
You can control cookie lifecycle by deleting or updating cookies through responses.
Knowing that cookie deletion is a message to the browser, not immediate removal, prevents confusion about cookie state.
7
ExpertCookie size limits and performance impact
🤔Before reading on: Do you think cookies can store unlimited data or have size limits? Commit to your answer.
Concept: Cookies have size limits (usually around 4KB) and are sent with every request, so large cookies can slow down your app.
Browsers limit cookie size per cookie and total cookies per domain. Sending large cookies wastes bandwidth and slows page loads. Experts keep cookies small and use other storage (like server sessions or localStorage) for bigger data.
Result
You avoid performance problems by managing cookie size and choosing the right storage method.
Understanding cookie size limits and their impact on network traffic is key to building fast, scalable web apps.
Under the Hood
Cookies are stored as key-value pairs in the browser and sent in HTTP headers named 'Cookie' with each request. When the server wants to set or change a cookie, it sends a 'Set-Cookie' header in the HTTP response. The browser then saves or updates the cookie accordingly. Cookies include metadata like expiration and security flags that the browser enforces. Flask accesses these headers through its request and response objects, abstracting the raw HTTP details.
Why designed this way?
HTTP is stateless, meaning each request is independent. Cookies were designed to add state by letting servers store small data on the client side. Using headers keeps cookies compatible with the HTTP protocol without changing it. This design balances simplicity, backward compatibility, and flexibility. Alternatives like URL parameters were less secure and messy, so cookies became the standard.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│   Browser     │       │    Network    │       │    Server     │
│               │       │               │       │               │
│ Stores cookie │       │               │       │ Reads cookie  │
│ Sends cookie  │──────▶│ HTTP Request  │──────▶│               │
│               │       │ (Cookie header)│       │               │
│               │       │               │       │ Sets cookie   │
│               │       │               │       │ (Set-Cookie)  │
│               │       │               │       │               │
│               │       │               │       │ Sends response│
│               │◀──────│ HTTP Response │◀──────│               │
│               │       │ (Set-Cookie)  │       │               │
└───────────────┘       └───────────────┘       └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think cookies are stored on the server or the client? Commit to your answer.
Common Belief:Cookies are stored on the server to keep track of users.
Tap to reveal reality
Reality:Cookies are stored on the client (browser), not the server. The server only sends instructions to set or delete cookies.
Why it matters:Thinking cookies are server-side can lead to security mistakes and confusion about how to manage user data.
Quick: Do you think cookies can store large files like images? Commit to your answer.
Common Belief:Cookies can store any amount of data, including large files.
Tap to reveal reality
Reality:Cookies have strict size limits (around 4KB) and cannot store large files. Large data should use other storage methods.
Why it matters:Trying to store too much data in cookies causes errors and slows down your app.
Quick: Do you think setting a cookie in Flask automatically makes it available in the next request? Commit to your answer.
Common Belief:Once you set a cookie in Flask, it is immediately available in the same request cycle.
Tap to reveal reality
Reality:Cookies set in the response are only sent to the browser and become available in subsequent requests, not the current one.
Why it matters:Expecting immediate availability leads to bugs where your app can't read newly set cookies until the next visit.
Quick: Do you think HttpOnly cookies can be accessed by JavaScript? Commit to your answer.
Common Belief:HttpOnly cookies can be read by JavaScript on the page.
Tap to reveal reality
Reality:HttpOnly cookies are inaccessible to JavaScript, protecting them from cross-site scripting attacks.
Why it matters:Misunderstanding this can cause security vulnerabilities by exposing sensitive cookies to scripts.
Expert Zone
1
Cookies set with the 'Secure' flag are only sent over HTTPS, preventing exposure on insecure connections.
2
The 'SameSite' attribute controls cross-site cookie sending, helping prevent CSRF attacks but can cause issues with third-party integrations.
3
Browsers limit the total number of cookies per domain, so managing cookie count is as important as size.
When NOT to use
Cookies are not suitable for storing large or sensitive data. For sensitive data, use server-side sessions with secure tokens. For large data, use browser storage like localStorage or IndexedDB. Also, avoid cookies for data that doesn't need to be sent with every request to reduce network overhead.
Production Patterns
In production, cookies are often used to store session IDs that link to server-side session data. Secure and HttpOnly flags are set to protect cookies. Developers use SameSite attributes to prevent CSRF. Cookies are kept minimal to optimize performance, and frameworks like Flask-Login handle cookie-based authentication securely.
Connections
HTTP Protocol
Cookies are part of HTTP headers used in requests and responses.
Understanding HTTP headers helps grasp how cookies travel between browser and server.
Web Security
Cookie attributes like HttpOnly and Secure relate directly to web security practices.
Knowing cookie security flags is essential to protect users from attacks like XSS and CSRF.
Human Memory
Cookies function like short-term memory notes that help websites remember users.
Seeing cookies as memory aids clarifies why they are limited in size and lifespan.
Common Pitfalls
#1Trying to read a cookie immediately after setting it in the same request.
Wrong approach:response = make_response('Set cookie') response.set_cookie('user', 'Alice') user = request.cookies.get('user') # This will be None return response
Correct approach:response = make_response('Set cookie') response.set_cookie('user', 'Alice') # Read cookie in a future request, not now return response
Root cause:Cookies set in the response are not available in the current request's cookie data.
#2Storing sensitive information like passwords directly in cookies.
Wrong approach:response.set_cookie('password', 'mypassword123')
Correct approach:Store only a session ID in the cookie and keep sensitive data securely on the server.
Root cause:Cookies can be read or intercepted if not properly secured, so sensitive data should never be stored directly.
#3Setting cookies without expiration, causing them to be session cookies unintentionally.
Wrong approach:response.set_cookie('theme', 'dark') # No expiration set
Correct approach:response.set_cookie('theme', 'dark', max_age=60*60*24*30) # Expires in 30 days
Root cause:Without expiration, cookies last only until the browser closes, which may not be the intended behavior.
Key Takeaways
Cookies are small pieces of data stored on the user's browser to help websites remember information between visits.
In Flask, you set cookies by adding them to the response object and read them from the request object.
Cookies have important attributes like expiration, HttpOnly, and Secure that control their behavior and security.
Cookies are limited in size and sent with every request, so keep them small to avoid performance issues.
Understanding how cookies work under the hood helps you avoid common mistakes and build secure, efficient web apps.

Practice

(1/5)
1. What is the main purpose of using cookies in a Flask web application?
easy
A. To increase the speed of the Flask server
B. To run server-side scripts automatically
C. To change the HTML structure of a webpage
D. To store small pieces of data on the user's browser for later use

Solution

  1. Step 1: Understand what cookies do

    Cookies store small data on the user's browser to remember information like login status or preferences.
  2. Step 2: Identify the correct purpose in Flask context

    Flask uses cookies to save data on the client side, not to run server scripts or change server speed.
  3. Final Answer:

    To store small pieces of data on the user's browser for later use -> Option D
  4. Quick Check:

    Cookies save data on browser = C [OK]
Hint: Cookies save data on browser, not server tasks [OK]
Common Mistakes:
  • Thinking cookies run server scripts
  • Confusing cookies with server speed optimization
  • Believing cookies change webpage HTML structure
2. Which of the following is the correct way to set a cookie named user_id with value 123 in Flask?
easy
A. response.cookies.set('user_id', 123)
B. response.set_cookie('user_id', '123')
C. request.set_cookie('user_id', '123')
D. request.cookies.set('user_id', '123')

Solution

  1. Step 1: Identify the correct method to set cookies

    Cookies are set on the response object using set_cookie method.
  2. Step 2: Check the value type and object used

    The value must be a string, so '123' is correct. Also, setting cookies on request object is invalid.
  3. Final Answer:

    response.set_cookie('user_id', '123') -> Option B
  4. Quick Check:

    Use response.set_cookie with string value = A [OK]
Hint: Use response.set_cookie with string values [OK]
Common Mistakes:
  • Using request object to set cookies
  • Passing integer instead of string as cookie value
  • Calling set_cookie on request.cookies
3. Given this Flask route code, what will be the output when accessing /get_cookie after setting the cookie username to alice?
from flask import Flask, request, make_response
app = Flask(__name__)

@app.route('/set_cookie')
def set_cookie():
    resp = make_response('Cookie Set')
    resp.set_cookie('username', 'alice')
    return resp

@app.route('/get_cookie')
def get_cookie():
    user = request.cookies.get('username')
    return f'User: {user}'
medium
A. User: alice
B. User: None
C. User: username
D. Error: Cookie not found

Solution

  1. Step 1: Understand cookie setting route

    The /set_cookie route sets a cookie named 'username' with value 'alice' on the response.
  2. Step 2: Understand cookie reading route

    The /get_cookie route reads the 'username' cookie from the request and returns it in the string.
  3. Final Answer:

    User: alice -> Option A
  4. Quick Check:

    Cookie 'username' = 'alice' read correctly = A [OK]
Hint: Set cookie first, then read with request.cookies.get() [OK]
Common Mistakes:
  • Expecting cookie value before setting it
  • Confusing cookie name with value
  • Assuming error if cookie missing without checking
4. Identify the error in this Flask code snippet that tries to read a cookie named session_id:
from flask import Flask, request
app = Flask(__name__)

@app.route('/check')
def check():
    session = request.cookies['session_id']
    return f'Session: {session}'
medium
A. Should use response.cookies instead of request.cookies
B. Cookie name must be capitalized as 'Session_id'
C. Using square brackets to access cookie may cause KeyError if cookie missing
D. Flask does not support reading cookies

Solution

  1. Step 1: Check how cookie is accessed

    The code uses request.cookies['session_id'] which raises KeyError if cookie is missing.
  2. Step 2: Suggest safer method

    Using request.cookies.get('session_id') returns None if cookie missing, avoiding error.
  3. Final Answer:

    Using square brackets to access cookie may cause KeyError if cookie missing -> Option C
  4. Quick Check:

    Access cookie safely with get() to avoid errors = B [OK]
Hint: Use request.cookies.get() to avoid KeyError [OK]
Common Mistakes:
  • Using response.cookies to read cookies
  • Assuming cookie names are case-insensitive
  • Ignoring possibility of missing cookies causing errors
5. You want to create a Flask route that sets a cookie named theme with value dark that expires in 7 days. Which code snippet correctly does this?
hard
A. resp.set_cookie('theme', 'dark', max_age=7*24*60*60)
B. resp.set_cookie('theme', 'dark', expires=7)
C. resp.set_cookie('theme', 'dark', max_age=7)
D. resp.set_cookie('theme', 'dark', expires='7 days')

Solution

  1. Step 1: Understand cookie expiration parameters

    To set expiration, use max_age in seconds or expires as a datetime object.
  2. Step 2: Calculate 7 days in seconds and check syntax

    7 days = 7*24*60*60 seconds. resp.set_cookie('theme', 'dark', max_age=7*24*60*60) uses max_age correctly with this calculation.
  3. Final Answer:

    resp.set_cookie('theme', 'dark', max_age=7*24*60*60) -> Option A
  4. Quick Check:

    Use max_age in seconds for 7 days = D [OK]
Hint: Use max_age in seconds for cookie expiry [OK]
Common Mistakes:
  • Passing expires as integer days instead of seconds or datetime
  • Using string '7 days' which is invalid
  • Confusing max_age and expires parameters
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard