Reputation: 51
I was going through a flask application and found the use of @app.teardown_request
.
Can anyone please demystify the real reason of using @app.teardown_request
rather than @app.teardown_appcontext
?
In other words what exactly is the difference?
Upvotes: 4
Views: 2612
Reputation: 1426
@app.teardown_request
Called after the request is dispatched and the response is returned, right before the request context is popped.
@app.teardown_appcontext
Registers a function to be called when the application context is popped. The application context is typically popped after the request context for each request, at the end of CLI commands, or after a manually pushed context ends.
There is a definitive timing and scope difference.
Upvotes: 1
Reputation: 587
@app.teardown_appcontext
- Bind a function after each request, even if an exception is encountered.
@app.teardown_request
- Registers a function to be called at the end of each request whether it was successful or an exception was raised. It is a good place to cleanup request scope objects like a database session/transaction.
https://github.com/pallets/flask-sqlalchemy/issues/379
Upvotes: 2