B. The route should accept GET method instead of POST
C. The form data might not include 'email', causing KeyError
D. request.form cannot be accessed directly
Solution
Step 1: Understand why KeyError occurs
Accessing request.form['email'] raises KeyError if 'email' is missing in the form data.
Step 2: Suggest safer access method
Use request.form.get('email') to avoid KeyError and get None if missing.
Final Answer:
The form data might not include 'email', causing KeyError -> Option C
Quick Check:
Missing key in form causes KeyError [OK]
Hint: Use .get() to avoid KeyError on missing form keys [OK]
Common Mistakes:
Assuming form always has the key
Confusing form data with query parameters
Thinking request.form is inaccessible
5. You want to check if a client sent a cookie named session_id in a Flask route. Which code snippet correctly checks for it and returns its value or 'No session' if missing?
A)
sid = request.cookies['session_id']
return sid if sid else 'No session'
B)
sid = request.cookies.get('session_id')
return sid or 'No session'
C)
sid = request.form.get('session_id')
return sid or 'No session'
D)
sid = request.args.get('session_id')
return sid or 'No session'
hard
A. Access cookie directly with [] and check truthiness
B. Use .get() on cookies and return fallback if missing
C. Check form data for cookie value
D. Check query parameters for cookie value
Solution
Step 1: Identify how to safely access cookies
Cookies are accessed via request.cookies. Using .get() avoids KeyError if cookie is missing.
Step 2: Return cookie value or fallback
Using sid or 'No session' returns the cookie value if present, else the fallback string.
Final Answer:
Use .get() on cookies and return fallback if missing -> Option B
Quick Check:
Cookies use request.cookies.get() safely [OK]
Hint: Use request.cookies.get('name') to avoid errors [OK]
Common Mistakes:
Accessing cookies with [] risking KeyError
Looking for cookies in form or args
Not providing fallback for missing cookie
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.