Complete the code to register a teardown function in Flask.
from flask import Flask app = Flask(__name__) @app.[1]() def cleanup(exception=None): print("Cleaning up after request")
The @app.teardown_request decorator registers a function to run after each request, even if an exception occurs.
Complete the code to access the exception object in a teardown function.
@app.teardown_request def cleanup([1]=None): if [1]: print(f"Exception occurred: [1]")
The teardown function receives an optional exception argument which is None if no error occurred.
Fix the error in the teardown function registration.
def cleanup(exception=None): print("Cleaning up") app.[1](cleanup)
app.before_request(cleanup) insteadapp.route(cleanup) which is for URL routesTo register a teardown function, use app.teardown_request decorator or call app.teardown_request(cleanup).
Fill both blanks to create a teardown function that closes a database connection.
@app.[1]() def close_db([2]=None): db = getattr(g, 'db', None) if db is not None: db.close()
before_request decoratorerrorThe teardown function uses @app.teardown_request and receives an exception argument.
Fill all three blanks to register a teardown function that logs errors and cleans up resources.
@app.[1]() def teardown([2]=None): if [2]: app.logger.error(f"Error: [2]") cleanup_resources()
before_request decoratorexception argument properlyThe function is decorated with @app.teardown_request and uses the exception argument to check for errors.