Performance: Teardown hooks
Teardown hooks affect the cleanup phase after a request, impacting server response time and resource release efficiency.
from flask import Flask app = Flask(__name__) @app.teardown_request def teardown(exception): db = get_db() if db: db.close() # Close connection promptly # Avoid heavy or blocking operations here
from flask import Flask import time app = Flask(__name__) @app.teardown_request def teardown(exception): # Closing database connection inefficiently db = get_db() db.close() # Heavy synchronous cleanup time.sleep(2) # Simulate slow cleanup
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Blocking teardown with slow cleanup | 0 | 0 | 0 | [X] Bad |
| Quick resource release in teardown | 0 | 0 | 0 | [OK] Good |
teardown_request function in Flask?@app.teardown_request, which optionally accepts an error parameter.error=None parameter to detect errors during the request.@app.teardown_request
def cleanup(error=None):
if error:
print('Error occurred')
else:
print('Request finished cleanly')error parameter is None if the request finished without errors.@app.teardown_request
def cleanup():
print('Cleaning up')error=None parameter to receive error info.cleanup has no parameters, so Flask will raise an error when calling it.Pass the test and this pattern moves unknown