I'm new to web development in Python and I've chosen Flask to start my web application. I have some resources to free before application shutdown, but I couldn't find where to put my cleanup code.
Flask provides some decorators like before_request
and teardown_request
to register callbacks before and after request processing. Is there something similar to register a callback to be called before the application stops?
Thanks.
Flask provides the g object for this purpose. It is a simple namespace object that has the same lifetime as an application context. Note. The g name stands for “global”, but that is referring to the data being global within a context.
Goto Task Manager. Find flask.exe. Select and End process.
The atexit
module allows you to register program termination callbacks. Its callbacks won't be called however if the application is terminated by a signal. If you need to handle those cases, you can register the same callbacks with the signal
module (for instance you might want to handle the SIGTERM signal).
I may have misunderstood what exactly you want to cleanup, but resources such as file handles or database connections will be closed anyway at interpreter shutdown, so you shouldn't have to worry about those.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With