Bird
Raised Fist0
Flaskframework~10 mins

Setting and reading cookies in Flask - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Setting and reading cookies
Client sends request
↓
Server reads cookies from request
↓
Server processes request
↓
Server sets cookies in response
↓
Response sent back to client with Set-Cookie header
↓
Client stores cookies
↓
Next request includes stored cookies
This flow shows how a client sends a request with cookies, the server reads them, processes the request, sets new cookies in the response, and the client stores them for future requests.
Execution Sample
Flask
from flask import Flask, request, make_response
app = Flask(__name__)

@app.route('/')
def index():
    user = request.cookies.get('user')
    resp = make_response(f'Hello {user}')
    resp.set_cookie('user', 'Alice')
    return resp
This Flask code reads a cookie named 'user' from the request and sets a cookie 'user' with value 'Alice' in the response.
Execution Table
StepActionRequest CookiesRead Cookie 'user'Set Cookie 'user'Response Content
1Client sends first request{}NoneSet 'user'='Alice'Hello None
2Client stores cookie 'user'='Alice'{}N/AN/AN/A
3Client sends second request with cookie{'user': 'Alice'}AliceSet 'user'='Alice'Hello Alice
💡 Execution stops after response is sent and client stores cookie for next requests.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3
request.cookies{}{}{}{'user': 'Alice'}
userNoneNoneNoneAlice
response cookie 'user'NoneAliceAliceAlice
Key Moments - 3 Insights
Why is 'user' None in the first response content?
Because the client did not send any 'user' cookie in the first request (see execution_table step 1), so request.cookies.get('user') returns None.
How does the cookie 'user' get sent back to the server in the second request?
After the first response, the client stores the cookie 'user=Alice' (execution_table step 2). The browser automatically includes this cookie in the next request headers (step 3).
Why does the server set the cookie 'user'='Alice' on every response?
The code calls resp.set_cookie('user', 'Alice') every time the route runs, so the server instructs the client to keep the cookie updated each response.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'user' read from cookies at step 1?
A'' (empty string)
B'Alice'
CNone
DError
💡 Hint
Check the 'Read Cookie user' column at step 1 in execution_table.
At which step does the client start sending the 'user' cookie back to the server?
AStep 3
BStep 2
CStep 1
DNever
💡 Hint
Look at the 'Request Cookies' column in execution_table to see when 'user' appears.
If the server did not call set_cookie, what would happen to the 'user' cookie in the client?
AIt would be deleted immediately
BIt would remain stored and sent back
CIt would never be stored
DIt would cause an error
💡 Hint
Cookies stay stored on the client until expired or deleted; server setting cookie updates or removes it.
Concept Snapshot
Flask cookies flow:
- Read cookies from request: request.cookies.get('name')
- Set cookies in response: resp.set_cookie('name', 'value')
- Client stores cookies and sends them in future requests
- Server can update cookies each response
- Cookies enable state across requests
Full Transcript
In Flask, cookies are small pieces of data stored on the client browser. When a client sends a request, the server can read cookies from request.cookies. The server can send cookies back by setting them in the response using resp.set_cookie. The client stores these cookies and includes them in future requests automatically. This allows the server to remember information about the client between requests. In the example, the server reads a cookie named 'user' and sets it to 'Alice' in every response. The first request has no cookies, so 'user' is None. After the first response, the client stores the cookie and sends it back in the next request, so the server reads 'Alice' as the user cookie.

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