0
0
Flaskframework~20 mins

Teardown hooks in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Teardown Hooks in Flask
📖 Scenario: You are building a simple Flask web app that needs to clean up resources after each request. This is important to avoid resource leaks, like open database connections.
🎯 Goal: Learn how to use Flask's teardown_appcontext decorator to run cleanup code automatically after each request finishes.
📋 What You'll Learn
Create a Flask app instance named app
Define a function called close_db that prints 'Closing database connection' when called
Register close_db as a teardown hook using @app.teardown_appcontext
Create a simple route / that returns 'Hello, Flask!'
💡 Why This Matters
🌍 Real World
Teardown hooks help clean up resources like database connections or files after each web request, preventing resource leaks.
💼 Career
Understanding teardown hooks is important for backend developers to write robust Flask applications that manage resources efficiently.
Progress0 / 4 steps
1
Create the Flask app instance
Import Flask from flask and create a Flask app instance called app.
Flask
Need a hint?

Use Flask(__name__) to create the app instance.

2
Define the teardown function
Define a function called close_db that takes one argument exception and prints 'Closing database connection' inside the function.
Flask
Need a hint?

The function must accept exception even if you don't use it.

3
Register the teardown hook
Use the @app.teardown_appcontext decorator to register the close_db function as a teardown hook.
Flask
Need a hint?

Place the decorator @app.teardown_appcontext right above the close_db function.

4
Add a simple route
Create a route for / using @app.route('/') that defines a function index returning the string 'Hello, Flask!'.
Flask
Need a hint?

Use @app.route('/') decorator and define index function returning the greeting string.