0
0
Flaskframework~10 mins

How cookies work in HTTP in Flask - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to set a cookie named 'user' with value 'Alice' in a Flask response.

Flask
from flask import Flask, make_response
app = Flask(__name__)

@app.route('/')
def index():
    resp = make_response('Hello World')
    resp.set_cookie('[1]', 'Alice')
    return resp
Drag options to blanks, or click blank then click option'
Auser
Bsession
Cusername
Dcookie
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong cookie name like 'session' or 'cookie' instead of 'user'.
Forgetting to call set_cookie on the response object.
2fill in blank
medium

Complete the code to read the cookie named 'user' from the Flask request.

Flask
from flask import Flask, request
app = Flask(__name__)

@app.route('/')
def index():
    user = request.cookies.get('[1]')
    return f'User is {user}'
Drag options to blanks, or click blank then click option'
Ausername
Bsession
Cuser
Dcookie
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different cookie name than the one set.
Trying to access cookies directly without using request.cookies.get().
3fill in blank
hard

Fix the error in the code to delete the cookie named 'user' in the Flask response.

Flask
from flask import Flask, make_response
app = Flask(__name__)

@app.route('/logout')
def logout():
    resp = make_response('Logged out')
    resp.[1]('user')
    return resp
Drag options to blanks, or click blank then click option'
Adelete_cookie
Bset_cookie
Cclear_cookie
Dremove_cookie
Attempts:
3 left
💡 Hint
Common Mistakes
Using a non-existent method like 'remove_cookie'.
Trying to delete cookie by setting it to None without proper method.
4fill in blank
hard

Fill both blanks to create a cookie named 'session_id' with value 'abc123' that expires in 1 day.

Flask
from flask import Flask, make_response
from datetime import timedelta
app = Flask(__name__)

@app.route('/set')
def set_cookie():
    resp = make_response('Cookie set')
    resp.set_cookie('[1]', '[2]', max_age=86400)
    return resp
Drag options to blanks, or click blank then click option'
Asession_id
Babc123
Cuser
Dtoken
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong cookie names or values.
Not setting max_age to control cookie expiration.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps cookie names to their values for cookies with names starting with 'sess'.

Flask
cookies = [1]: [2] for [3] in request.cookies if [3].startswith('sess')}
Drag options to blanks, or click blank then click option'
Aname
Brequest.cookies[name]
Dcookie
Frequest.cookies[cookie]
Attempts:
3 left
💡 Hint
Common Mistakes
Using inconsistent variable names in the comprehension.
Trying to use the cookie value as the loop variable.