How to Use teardown_request in Flask for Cleanup Tasks
In Flask, use the
@app.teardown_request decorator to register a function that runs after each request, regardless of exceptions. This function receives an optional exception argument and is ideal for cleaning up resources like database connections.Syntax
The @app.teardown_request decorator registers a function that Flask calls after each request finishes. The function must accept one argument, which is either None or an exception object if an error occurred during the request.
This function runs after the response is sent, making it perfect for cleanup tasks.
python
from flask import Flask app = Flask(__name__) @app.teardown_request def cleanup(exception): if exception: print(f"An error occurred: {exception}") else: print("Request finished successfully.")
Example
This example shows a Flask app that opens a fake database connection before each request and closes it after the request using teardown_request. It prints messages to the console to demonstrate when the cleanup runs.
python
from flask import Flask, g app = Flask(__name__) @app.before_request def open_db(): g.db = "Database connection opened" print(g.db) @app.route('/') def index(): return "Hello, Flask!" @app.teardown_request def close_db(exception): db = getattr(g, 'db', None) if db is not None: print("Closing database connection") if exception: print(f"Exception during request: {exception}") if __name__ == '__main__': app.run(debug=True)
Output
Database connection opened
Closing database connection
Common Pitfalls
- Not accepting the exception argument: The teardown function must accept one argument, even if unused, or Flask will raise an error.
- Raising exceptions inside teardown: Avoid raising exceptions in teardown functions because they can hide the original error or cause confusing behavior.
- Assuming teardown runs before response: Teardown functions run after the response is sent, so do not modify the response here.
python
from flask import Flask app = Flask(__name__) # Wrong: teardown function without argument @app.teardown_request def bad_teardown(): print("This will cause an error") # Correct: @app.teardown_request def good_teardown(exception): print("Proper teardown function")
Quick Reference
@app.teardown_request: Decorator to register a teardown function.- Function signature:
def func(exception): - Runs after each request, even if an error occurred.
- Use for cleanup like closing database connections or releasing resources.
- Do not modify the response in teardown functions.
Key Takeaways
Use @app.teardown_request to run cleanup code after every request in Flask.
The teardown function must accept one argument for the exception or None.
Teardown functions run after the response is sent, so avoid modifying the response there.
Avoid raising exceptions inside teardown functions to prevent hiding original errors.
Common use cases include closing database connections and releasing resources.