Cookies help websites remember you. You can save small bits of information on a visitor's browser and read it later.
Setting and reading cookies in Flask
from flask import Flask, request, make_response app = Flask(__name__) @app.route('/set') def set_cookie(): resp = make_response('Cookie is set') resp.set_cookie('key', 'value') return resp @app.route('/get') def get_cookie(): value = request.cookies.get('key') return f'Cookie value is {value}'
Use make_response() to create a response object before setting cookies.
Read cookies from request.cookies dictionary.
username with value alice.resp.set_cookie('username', 'alice')
username. Returns None if not found.value = request.cookies.get('username')resp.set_cookie('session_id', 'abc123', max_age=3600)
This Flask app has two routes: /set sets a cookie named favorite_color with value blue that lasts one day. /get reads and shows the cookie value if it exists.
from flask import Flask, request, make_response app = Flask(__name__) @app.route('/set') def set_cookie(): resp = make_response('Cookie has been set!') resp.set_cookie('favorite_color', 'blue', max_age=60*60*24) # 1 day return resp @app.route('/get') def get_cookie(): color = request.cookies.get('favorite_color') if color: return f'Your favorite color is {color}' else: return 'No favorite color cookie found.'
Cookies are stored on the user's browser and sent with every request to your site.
Be careful not to store sensitive information in cookies because users can see and change them.
Use max_age or expires to control how long cookies last.
Cookies let you save small data on a user's browser to remember things.
Use set_cookie on a response to save a cookie.
Use request.cookies.get() to read a cookie value.
Practice
Solution
Step 1: Understand what cookies do
Cookies store small data on the user's browser to remember information like login status or preferences.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.Final Answer:
To store small pieces of data on the user's browser for later use -> Option DQuick Check:
Cookies save data on browser = C [OK]
- Thinking cookies run server scripts
- Confusing cookies with server speed optimization
- Believing cookies change webpage HTML structure
user_id with value 123 in Flask?Solution
Step 1: Identify the correct method to set cookies
Cookies are set on the response object usingset_cookiemethod.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.Final Answer:
response.set_cookie('user_id', '123') -> Option BQuick Check:
Use response.set_cookie with string value = A [OK]
- Using request object to set cookies
- Passing integer instead of string as cookie value
- Calling set_cookie on request.cookies
/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}'Solution
Step 1: Understand cookie setting route
The/set_cookieroute sets a cookie named 'username' with value 'alice' on the response.Step 2: Understand cookie reading route
The/get_cookieroute reads the 'username' cookie from the request and returns it in the string.Final Answer:
User: alice -> Option AQuick Check:
Cookie 'username' = 'alice' read correctly = A [OK]
- Expecting cookie value before setting it
- Confusing cookie name with value
- Assuming error if cookie missing without checking
session_id:
from flask import Flask, request
app = Flask(__name__)
@app.route('/check')
def check():
session = request.cookies['session_id']
return f'Session: {session}'Solution
Step 1: Check how cookie is accessed
The code usesrequest.cookies['session_id']which raises KeyError if cookie is missing.Step 2: Suggest safer method
Usingrequest.cookies.get('session_id')returns None if cookie missing, avoiding error.Final Answer:
Using square brackets to access cookie may cause KeyError if cookie missing -> Option CQuick Check:
Access cookie safely with get() to avoid errors = B [OK]
- Using response.cookies to read cookies
- Assuming cookie names are case-insensitive
- Ignoring possibility of missing cookies causing errors
theme with value dark that expires in 7 days. Which code snippet correctly does this?Solution
Step 1: Understand cookie expiration parameters
To set expiration, usemax_agein seconds orexpiresas a datetime object.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.Final Answer:
resp.set_cookie('theme', 'dark', max_age=7*24*60*60) -> Option AQuick Check:
Use max_age in seconds for 7 days = D [OK]
- Passing expires as integer days instead of seconds or datetime
- Using string '7 days' which is invalid
- Confusing max_age and expires parameters
Ready to prove it?
Pass the test and this pattern moves unknown
