Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do I put cleanup code in a Flask application? [duplicate]

Tags:

python

flask

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.

like image 771
Leo Lobeto Avatar asked May 29 '12 07:05

Leo Lobeto


People also ask

What is G in Flask?

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.

How do I close a Flask app in terminal?

Goto Task Manager. Find flask.exe. Select and End process.


1 Answers

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.

like image 57
jd. Avatar answered Oct 16 '22 16:10

jd.