Bird
Raised Fist0
Flaskframework~10 mins

Teardown hooks in Flask - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Teardown hooks
Request starts
↓
Before request handlers
↓
View function runs
↓
Response generated
↓
Teardown hooks run
↓
Request ends
This flow shows how Flask runs teardown hooks after the response is ready, to clean up resources.
Execution Sample
Flask
from flask import Flask, g
app = Flask(__name__)

@app.teardown_request
def teardown(exception=None):
    print('Teardown hook runs')
This code registers a teardown hook that runs after each request to perform cleanup.
Execution Table
StepEventExceptionActionOutput
1Request startsNoneStart processing requestNo output
2View function runsNoneProcess request logicResponse created
3Response readyNonePrepare to send responseResponse sent
4Teardown hook runsNoneRun teardown_request functionPrints 'Teardown hook runs'
5Request endsNoneCleanup completeNo output
💡 Request processing finished, teardown hooks executed after response sent
Variable Tracker
VariableStartAfter Step 2After Step 4Final
exceptionNoneNoneNoneNone
gEmptyMay hold request dataCleared or unchangedEmpty or reset
Key Moments - 2 Insights
Why does the teardown hook run even if the view function raises an error?
Because teardown hooks run after the response or error handling, as shown in step 4 of the execution_table, ensuring cleanup always happens.
Can the teardown hook access the exception that caused the error?
Yes, the exception parameter in the teardown function receives the error if any, as shown in the variable 'exception' in variable_tracker.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is printed during the teardown hook step?
A'Teardown hook runs'
B'Request starts'
C'Response created'
D'Cleanup complete'
💡 Hint
Check the 'Output' column at step 4 in the execution_table.
At which step does the response get sent to the client?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Event' and 'Action' columns in the execution_table for when the response is sent.
If an exception occurs in the view function, what value does the 'exception' variable have in the teardown hook?
AA string 'error'
BNone
CThe exception object
DIt is undefined
💡 Hint
Refer to the 'exception' variable in variable_tracker and the teardown function parameter.
Concept Snapshot
Flask teardown hooks run after each request finishes.
Use @app.teardown_request decorator.
They receive an optional exception argument.
Useful for cleaning resources like DB connections.
Run even if errors occur in the view.
Executed after response is sent.
Full Transcript
In Flask, teardown hooks are functions that run after each request finishes processing. They are registered using the @app.teardown_request decorator. These hooks run after the response is sent to the client, allowing you to clean up resources such as database connections. The teardown function receives an optional exception argument that contains any error raised during the request. This ensures cleanup happens even if the view function raises an error. The execution flow starts with the request, runs the view, sends the response, then runs teardown hooks before ending the request.

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