Bird
Raised Fist0
Flaskframework~20 mins

Teardown hooks in Flask - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Teardown Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when a Flask teardown hook raises an exception?
Consider a Flask app with a teardown hook that raises an exception. What is the behavior of the app after a request finishes?
Flask
from flask import Flask
app = Flask(__name__)

@app.teardown_request
def teardown(exception):
    raise Exception('Error in teardown')

@app.route('/')
def index():
    return 'Hello World'

if __name__ == '__main__':
    app.run()
AThe exception is logged but does not affect the response sent to the client.
BThe exception causes the server to crash and no response is sent.
CThe exception modifies the response body to include the error message.
DThe exception is ignored silently without any logging.
Attempts:
2 left
💡 Hint
Think about how Flask handles errors in teardown hooks after the response is sent.
❓ state_output
intermediate
2:00remaining
What is the output count of teardown calls after multiple requests?
Given this Flask app, how many times will the teardown function print 'Teardown called' after 3 requests to '/'?
Flask
from flask import Flask
app = Flask(__name__)

count = 0

@app.teardown_request
def teardown(exception):
    global count
    count += 1
    print('Teardown called')

@app.route('/')
def index():
    return 'Hi'

if __name__ == '__main__':
    app.run()
A0
B1
C3
D6
Attempts:
2 left
💡 Hint
Teardown hooks run once per request after the response.
📝 Syntax
advanced
2:00remaining
Which option correctly registers a teardown hook for the application context?
Select the correct way to register a teardown function that runs when the Flask application context ends.
A
@app.teardown_app_context
def teardown_appcontext(exception):
    print('App context teardown')
B
@app.teardown_request
def teardown_appcontext(exception):
    print('App context teardown')
C
@app.teardown
def teardown_appcontext(exception):
    print('App context teardown')
D
@app.teardown_appcontext
def teardown_appcontext(exception):
    print('App context teardown')
Attempts:
2 left
💡 Hint
Check the exact decorator name for application context teardown.
🔧 Debug
advanced
2:00remaining
Why does this teardown hook not run after a request?
Identify the reason why the teardown function below never executes after requests.
Flask
from flask import Flask
app = Flask(__name__)

@app.teardown_request
def teardown():
    print('Teardown executed')

@app.route('/')
def index():
    return 'Hello'

if __name__ == '__main__':
    app.run()
AThe decorator @app.teardown_request is invalid and should be @app.teardown.
BThe teardown function must accept an exception argument even if unused.
CThe function name 'teardown' is reserved and causes a conflict.
DTeardown functions only run on error responses, not successful ones.
Attempts:
2 left
💡 Hint
Check the function signature required by teardown_request hooks.
🧠 Conceptual
expert
2:00remaining
What is the main difference between @app.teardown_request and @app.teardown_appcontext?
Choose the statement that best describes the difference between these two Flask teardown decorators.
A@app.teardown_request runs after each request; @app.teardown_appcontext runs when the app context ends, which may be less frequent.
B@app.teardown_request runs only on errors; @app.teardown_appcontext runs after every request.
C@app.teardown_request runs before the request starts; @app.teardown_appcontext runs after the request ends.
D@app.teardown_request and @app.teardown_appcontext are aliases and behave identically.
Attempts:
2 left
💡 Hint
Think about the lifecycle of a request versus the application context.

Practice

(1/5)
1. What is the main purpose of a teardown_request function in Flask?
easy
A. To handle incoming HTTP requests
B. To define URL routes
C. To start a new request
D. To run cleanup code after each request finishes

Solution

  1. Step 1: Understand the role of teardown hooks

    Teardown hooks run after a request ends to clean up resources like files or database connections.
  2. Step 2: Match the purpose with options

    Only To run cleanup code after each request finishes describes running cleanup code after each request finishes, which matches the teardown hook purpose.
  3. Final Answer:

    To run cleanup code after each request finishes -> Option D
  4. Quick Check:

    Teardown hooks = cleanup after request [OK]
Hint: Teardown hooks always run after request ends [OK]
Common Mistakes:
  • Confusing teardown with request handling
  • Thinking teardown runs before request
  • Assuming teardown defines routes
2. Which of the following is the correct way to register a teardown function in Flask?
easy
A. @app.teardown_request def cleanup(error=None): pass
B. @app.after_request def cleanup(): pass
C. @app.route('/teardown') def cleanup(): pass
D. @app.before_request def cleanup(): pass

Solution

  1. Step 1: Identify the correct decorator for teardown

    The correct decorator to register a teardown function is @app.teardown_request, which optionally accepts an error parameter.
  2. Step 2: Check function signature

    The function should accept an optional error=None parameter to detect errors during the request.
  3. Final Answer:

    @app.teardown_request\ndef cleanup(error=None): pass -> Option A
  4. Quick Check:

    Teardown decorator = @app.teardown_request [OK]
Hint: Teardown functions use @app.teardown_request with error param [OK]
Common Mistakes:
  • Using @app.before_request instead
  • Missing the optional error parameter
  • Confusing with @app.after_request
3. Given this Flask code snippet, what will be printed after a request completes successfully (no error)?
@app.teardown_request
def cleanup(error=None):
    if error:
        print('Error occurred')
    else:
        print('Request finished cleanly')
medium
A. Error occurred
B. Request finished cleanly
C. No output
D. SyntaxError

Solution

  1. Step 1: Understand the error parameter in teardown

    The error parameter is None if the request finished without errors.
  2. Step 2: Trace the if-else logic

    Since error is None, the else branch runs, printing 'Request finished cleanly'.
  3. Final Answer:

    Request finished cleanly -> Option B
  4. Quick Check:

    error=None means clean finish [OK]
Hint: error=None means no error, so else branch runs [OK]
Common Mistakes:
  • Assuming error is always True
  • Expecting no output
  • Confusing teardown with before_request
4. What is wrong with this teardown function?
@app.teardown_request
def cleanup():
    print('Cleaning up')
medium
A. Decorator should be @app.before_request
B. Using print inside teardown is not allowed
C. Missing the optional error parameter in the function
D. Function name must be 'teardown' exactly

Solution

  1. Step 1: Check teardown function signature

    Teardown functions must accept an optional error=None parameter to receive error info.
  2. Step 2: Identify missing parameter issue

    The function cleanup has no parameters, so Flask will raise an error when calling it.
  3. Final Answer:

    Missing the optional error parameter in the function -> Option C
  4. Quick Check:

    Teardown needs error param or it fails [OK]
Hint: Teardown functions must accept error=None parameter [OK]
Common Mistakes:
  • Omitting error parameter
  • Using wrong decorator
  • Thinking function name is fixed
5. You want to close a database connection after every request, but only if it was opened during that request. Which is the best way to do this using a teardown hook?
hard
A. Use @app.teardown_request with a function that checks if the connection exists and closes it
B. Use @app.before_request to close the connection before the request starts
C. Use @app.route to close the connection on a specific URL
D. Use @app.after_request to close the connection without checking if it exists

Solution

  1. Step 1: Understand when to close resources

    Resources like database connections should be closed after the request ends, not before or on specific routes.
  2. Step 2: Use teardown_request with conditional check

    The teardown function can check if the connection was opened during the request and close it safely.
  3. Final Answer:

    Use @app.teardown_request with a function that checks if the connection exists and closes it -> Option A
  4. Quick Check:

    Teardown + check connection before closing = best practice [OK]
Hint: Close resources in teardown only if they exist [OK]
Common Mistakes:
  • Closing connection before request starts
  • Closing without checking if connection exists
  • Trying to close on specific route only
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