Last modified: Nov 15, 2024 By Alexander Williams
Flask Teardown Request: Clean Up Resources After Requests
Flask's teardown_request()
is a powerful feature that helps developers manage and clean up resources after each request, regardless of whether the request was successful or encountered an error.
Understanding Teardown Request
Similar to how before_request handles operations before requests, teardown_request executes after the response has been constructed.
Unlike after_request, teardown_request runs even if an exception occurs during request processing, making it ideal for cleanup operations.
Basic Implementation
from flask import Flask, g
app = Flask(__name__)
@app.teardown_request
def cleanup_resources(exception=None):
if hasattr(g, 'db_connection'):
g.db_connection.close()
print("Database connection closed")
@app.route('/')
def index():
# Simulate database connection
g.db_connection = "Database Connection"
return "Hello World!"
Handling Exceptions
The teardown_request function receives an exception parameter that contains any error that occurred during request processing.
@app.teardown_request
def handle_cleanup(error=None):
if error:
print(f"An error occurred: {error}")
# Cleanup operations
print("Cleanup completed")
Multiple Teardown Functions
You can register multiple teardown request functions. They will execute in the reverse order they were registered.
@app.teardown_request
def cleanup_first(exception=None):
print("First cleanup")
@app.teardown_request
def cleanup_second(exception=None):
print("Second cleanup")
Second cleanup
First cleanup
Practical Use Cases
Common use cases for teardown_request()
include closing database connections, cleaning up temporary files, and releasing system resources.
from flask import Flask, g
import sqlite3
app = Flask(__name__)
def get_db():
if 'db' not in g:
g.db = sqlite3.connect('database.db')
return g.db
@app.teardown_request
def close_db(error):
db = g.pop('db', None)
if db is not None:
db.close()
Best Practices
- Always handle exceptions gracefully in teardown functions
- Keep teardown operations lightweight and focused
- Use Flask's g object for storing request-scoped resources
Conclusion
teardown_request()
is essential for maintaining clean and efficient Flask applications. It ensures proper resource cleanup and helps prevent memory leaks and resource exhaustion.
Remember to implement error handling and keep your teardown functions focused on cleanup operations for optimal application performance.