0
0
Flaskframework~5 mins

Teardown hooks in Flask

Choose your learning style9 modes available
Introduction

Teardown hooks let you run code after a web request finishes. This helps clean up resources like database connections.

Closing a database connection after handling a web request
Releasing file handles or network connections used during a request
Logging information once a request is fully processed
Cleaning up temporary data created during a request
Syntax
Flask
@app.teardown_request
def teardown_func(error=None):
    # cleanup code here

The function runs after each request, even if there was an error.

The optional error parameter tells if the request ended with an error.

Examples
This closes the database connection stored in Flask's g object after each request.
Flask
@app.teardown_request
def close_db(error=None):
    if hasattr(g, 'db'):
        g.db.close()
This logs whether the request finished with or without an error.
Flask
@app.teardown_request
def log_request(error=None):
    if error:
        print(f"Request ended with error: {error}")
    else:
        print("Request finished successfully")
Sample Program

This Flask app opens a dummy database connection before each request and closes it after the request finishes. The teardown hook prints a message when closing.

Flask
from flask import Flask, g

app = Flask(__name__)

@app.before_request
def open_db():
    g.db = open('dummy_db_connection', 'w')

@app.route('/')
def index():
    g.db.write('Hello')
    return 'Hello World'

@app.teardown_request
def close_db(error=None):
    if hasattr(g, 'db'):
        g.db.close()
        print('Database connection closed')

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Teardown hooks run even if your view function raises an error.

Use teardown hooks to avoid resource leaks in your app.

Summary

Teardown hooks run code after each request ends.

They help clean up resources like files or database connections.

The function can check if the request had an error using the optional parameter.