Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to import the session object from Flask.
Flask
from flask import Flask, [1]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Importing
request instead of session.Forgetting to import
session.✗ Incorrect
The session object is imported from Flask to store user session data.
2fill in blank
mediumComplete the code to set a secret key needed for session management.
Flask
app = Flask(__name__)
app.secret_key = [1] Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a number instead of a string for the secret key.
Setting the secret key to None or True.
✗ Incorrect
The secret key must be a string used to encrypt session data.
3fill in blank
hardFix the error in the code to store a username in the session.
Flask
from flask import Flask, session app = Flask(__name__) app.secret_key = 'key' @app.route('/login') def login(): session[1]['username'] = 'Alice' return 'Logged in'
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using dot notation like
session.set which is invalid.Trying to use
session.add which does not exist.✗ Incorrect
Session acts like a dictionary, so use square brackets to set a key.
4fill in blank
hardFill both blanks to check if 'username' is in session and retrieve it safely.
Flask
from flask import session if [1] in session: user = session.[2]('username') else: user = 'Guest'
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for variable
username instead of string 'username'.Using
pop which removes the key instead of just getting it.✗ Incorrect
Check if the string key 'username' is in session, then use get to retrieve it safely.
5fill in blank
hardFill all three blanks to clear the session and redirect to home page.
Flask
from flask import session, redirect, url_for @app.route('/logout') def logout(): session.[1]() return [2]( [3]('home') )
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using
pop without a key to clear session.Forgetting to use
redirect or url_for.✗ Incorrect
Use clear() to empty session, then redirect to the URL generated by url_for.