Bird
Raised Fist0
Flaskframework~20 mins

Context lifecycle execution in Flask - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Flask Context Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2: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}"
AMethod used: None
BMethod used: GET
CRuntimeError: Working outside of request context.
DMethod used: POST
Attempts:
2 left
💡 Hint
Think about the default HTTP method when you visit a URL in a browser.
❓ lifecycle
intermediate
2:00remaining
Order of Flask context teardown
Which of the following statements correctly describes when Flask's teardown_request functions are called?
AAfter the response is sent to the client, even if an exception occurred during request handling.
BBefore the request function is called, to prepare the context.
COnly if the request function completes without exceptions.
DOnly when the Flask app is shutting down.
Attempts:
2 left
💡 Hint
Think about cleanup tasks that must run regardless of errors.
🔧 Debug
advanced
2: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)
ANameError: name 'request' is not defined
BAttributeError: 'LocalProxy' object has no attribute 'method'
CRuntimeError: Working outside of request context.
DTypeError: 'method' is not callable
Attempts:
2 left
💡 Hint
Flask's request object requires an active request context to work.
❓ state_output
advanced
2: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__)
A
10
RuntimeError
B
10
AttributeError
C
10
10
D
RuntimeError
RuntimeError
Attempts:
2 left
💡 Hint
Consider when the application context is active and when it ends.
🧠 Conceptual
expert
2:00remaining
Understanding Flask context locals
Which statement best explains why Flask uses context locals like request and g instead of global variables?
ATo prevent any data from being stored during a request lifecycle.
BTo improve performance by caching data globally across all requests.
CTo allow global variables to be shared between different Flask apps in the same process.
DTo ensure each request has its own separate data, avoiding conflicts in concurrent requests.
Attempts:
2 left
💡 Hint
Think about what happens when many users use the app at the same time.

Practice

(1/5)
1. What is the main purpose of Flask's before_request function in the context lifecycle?
easy
A. To run code before each request to prepare data or resources
B. To clean up resources after a request finishes
C. To handle errors during a request
D. To define the URL routes for the application

Solution

  1. Step 1: Understand the role of before_request

    This function runs before each request to set up anything needed during the request.
  2. Step 2: Compare with other lifecycle hooks

    after_request cleans up after requests, error handlers manage errors, and routes define URLs.
  3. Final Answer:

    To run code before each request to prepare data or resources -> Option A
  4. Quick Check:

    before_request runs before request [OK]
Hint: Remember: before_request runs setup code before handling requests [OK]
Common Mistakes:
  • Confusing before_request with after_request
  • Thinking before_request handles errors
  • Mixing route definitions with lifecycle hooks
2. Which of the following is the correct way to store data for the current request using Flask's context?
easy
A. Store data in the g object inside a before_request function
B. Use a global variable outside the request
C. Save data in a class variable of the Flask app
D. Write data directly to the response object

Solution

  1. Step 1: Identify how Flask manages request-specific data

    Flask provides the g object to store data unique to each request.
  2. Step 2: Confirm correct usage

    Using g inside before_request ensures data is set up before route handlers run.
  3. Final Answer:

    Store data in the g object inside a before_request function -> Option A
  4. Quick Check:

    g stores request data [OK]
Hint: Use g for request data, not globals [OK]
Common Mistakes:
  • Using global variables that persist across requests
  • Trying to store request data in app class variables
  • Modifying the response object directly for data storage
3. Given this Flask code snippet, what will be printed when a request is made to /hello?
from flask import Flask, g
app = Flask(__name__)

@app.before_request
def before():
    g.message = 'Hi'

@app.route('/hello')
def hello():
    return g.message + ' there!'
medium
A. there!
B. Error: g.message not set
C. Hi there!
D. Hi

Solution

  1. Step 1: Analyze the before_request function

    The function sets g.message to 'Hi' before the route runs.
  2. Step 2: Check the route handler output

    The route returns g.message + ' there!', which becomes 'Hi there!'.
  3. Final Answer:

    Hi there! -> Option C
  4. Quick Check:

    g.message set before route [OK]
Hint: before_request sets g data used in routes [OK]
Common Mistakes:
  • Assuming g.message is not set yet
  • Forgetting before_request runs before routes
  • Expecting an error due to missing g attribute
4. What is wrong with this Flask code that tries to use g outside a request context?
from flask import Flask, g
app = Flask(__name__)

g.message = 'Hello'

@app.route('/')
def index():
    return g.message
medium
A. The g object cannot store strings
B. The route function is missing a return statement
C. The app is missing a secret key
D. Accessing g outside a request causes a runtime error

Solution

  1. Step 1: Identify where g is assigned

    g.message = 'Hello' is set outside any request or app context.
  2. Step 2: Understand Flask context rules

    g is only available during a request context; accessing it outside causes an error.
  3. Final Answer:

    Accessing g outside a request causes a runtime error -> Option D
  4. Quick Check:

    g only valid inside requests [OK]
Hint: Set g only inside request functions [OK]
Common Mistakes:
  • Setting g variables globally outside requests
  • Confusing g with global variables
  • Ignoring Flask's context lifecycle rules
5. You want to log the time taken by each request in your Flask app. Which is the best way to do this using context lifecycle hooks?
hard
A. Use teardown_request to set start time and before_request to log duration
B. Use before_request to store start time in g, and after_request to calculate and log duration
C. Log the time only inside the route without lifecycle hooks
D. Store start time in a global variable and log it in the route function

Solution

  1. Step 1: Use before_request to mark start time

    Store the current time in g.start_time before the request runs.
  2. Step 2: Use after_request to calculate duration and log

    Calculate elapsed time using current time minus g.start_time and log it, then return the response.
  3. Final Answer:

    Use before_request to store start time in g, and after_request to calculate and log duration -> Option B
  4. Quick Check:

    Use before_request and after_request for timing [OK]
Hint: Start timer before, log after request finishes [OK]
Common Mistakes:
  • Using global variables instead of g
  • Logging time only inside routes missing full request duration
  • Mixing up lifecycle hook order
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard