Challenge - 5 Problems
Flask Context Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate2:00remaining
Flask request context availability
In a Flask app, what will be the output of this code snippet when accessing the '/' route?
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def index():
return f"Method used: {request.method}"Flask
from flask import Flask, request app = Flask(__name__) @app.route('/') def index(): return f"Method used: {request.method}"
Attempts:
2 left
💡 Hint
Think about the default HTTP method when you visit a URL in a browser.
✗ Incorrect
When you visit a route in a browser, the HTTP method is GET by default. Flask's request context is active during the route function, so accessing request.method returns 'GET'.
❓ lifecycle
intermediate2:00remaining
Order of Flask context teardown
Which of the following statements correctly describes when Flask's
teardown_request functions are called?Attempts:
2 left
💡 Hint
Think about cleanup tasks that must run regardless of errors.
✗ Incorrect
teardown_request functions run after the response is returned, even if an error happened, to clean up resources.🔧 Debug
advanced2:00remaining
Identifying context errors in Flask
What error will this Flask code raise when executed outside a request?
from flask import request print(request.method)
Flask
from flask import request print(request.method)
Attempts:
2 left
💡 Hint
Flask's request object requires an active request context to work.
✗ Incorrect
Accessing request attributes outside a request context raises a RuntimeError indicating the context is missing.
❓ state_output
advanced2:00remaining
Flask application context variable behavior
Given this Flask code, what will be printed?
from flask import Flask, g
app = Flask(__name__)
with app.app_context():
g.value = 10
print(g.value)
try:
print(g.value)
except Exception as e:
print(type(e).__name__)Flask
from flask import Flask, g app = Flask(__name__) with app.app_context(): g.value = 10 print(g.value) try: print(g.value) except Exception as e: print(type(e).__name__)
Attempts:
2 left
💡 Hint
Consider when the application context is active and when it ends.
✗ Incorrect
Inside the app context, g.value is set and printed as 10. Outside, accessing g.value raises RuntimeError because the context ended.
🧠 Conceptual
expert2:00remaining
Understanding Flask context locals
Which statement best explains why Flask uses context locals like
request and g instead of global variables?Attempts:
2 left
💡 Hint
Think about what happens when many users use the app at the same time.
✗ Incorrect
Flask uses context locals to keep data isolated per request, so concurrent users do not interfere with each other's data.