0
0
Flaskframework~10 mins

Setting and reading cookies in Flask - Interactive Code 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 'username' with value 'Alice'.

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

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

Complete the code to read the cookie named 'username' from the request.

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

@app.route('/get')
def get_cookie():
    user = request.cookies.get('[1]')
    return f'User is {user}'
Drag options to blanks, or click blank then click option'
Auser
Busername
Cname
Dsession
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong cookie name like 'user' or 'session'.
Trying to access cookies directly without using request.cookies.get().
3fill in blank
hard

Fix the error in the code to set a cookie with expiration of 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('token', 'abc123', max_age=[1])
    return resp
Drag options to blanks, or click blank then click option'
A86400
Btimedelta(days=1)
C24*60*60*1000
DNone
Attempts:
3 left
💡 Hint
Common Mistakes
Passing a timedelta object instead of seconds.
Using milliseconds instead of seconds.
Passing None which disables expiration.
4fill in blank
hard

Fill both blanks to set a cookie named 'sessionid' with value 'xyz' that expires in 2 hours.

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

@app.route('/session')
def session_cookie():
    resp = make_response('Session cookie set')
    resp.set_cookie('[1]', '[2]', max_age=7200)
    return resp
Drag options to blanks, or click blank then click option'
Asessionid
Buserid
Cxyz
Dabc
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping cookie name and value.
Using wrong cookie names or values.
5fill in blank
hard

Fill all three blanks to read a cookie named 'auth' and return 'Logged in' if it exists, else 'Not logged in'.

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

@app.route('/auth')
def check_auth():
    token = request.cookies.get('[1]')
    if token [2] None:
        return '[3]'
    else:
        return 'Not logged in'
Drag options to blanks, or click blank then click option'
Aauth
B!=
CLogged in
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong cookie name.
Using wrong comparison operator.
Returning wrong strings.