Complete the code to set a cookie named 'user' with value 'Alice' in a Flask response.
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
The set_cookie method requires the cookie name as the first argument. Here, the cookie name is 'user'.
Complete the code to read the cookie named 'user' from the Flask request.
from flask import Flask, request app = Flask(__name__) @app.route('/') def index(): user = request.cookies.get('[1]') return f'User is {user}'
request.cookies.get().To read a cookie, use request.cookies.get() with the cookie name. Here, the cookie name is 'user'.
Fix the error in the code to delete the cookie named 'user' in the Flask response.
from flask import Flask, make_response app = Flask(__name__) @app.route('/logout') def logout(): resp = make_response('Logged out') resp.[1]('user') return resp
To delete a cookie in Flask, call resp.delete_cookie('user'). This instructs the browser to remove the cookie by setting its expiration time to the past.
Fill both blanks to create a cookie named 'session_id' with value 'abc123' that expires in 1 day.
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
The first blank is the cookie name 'session_id'. The second blank is the cookie value 'abc123'. The max_age=86400 sets the cookie to expire in 1 day (86400 seconds).
Fill all three blanks to create a dictionary comprehension that maps cookie names to their values for cookies with names starting with 'sess'.
cookies = [1]: [2] for [3] in request.cookies if [3].startswith('sess')}
The dictionary comprehension uses name as the variable for cookie names. The key is name, the value is request.cookies[name], and the loop variable is name. This collects all cookies whose names start with 'sess'.