8

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.

Leo Lobeto
  • 364
  • 3
  • 14
  • I don't know a facility offered by Flask when the application stops. It would be interesting to know what exactly you want to cleanup. Python has the `atexit` module, which may be what you are looking for. – jd. May 29 '12 at 08:04
  • I'm using a neo4j database and I keep a connection pool. I suppose atexit would do the job. Is it the more appropriate place to put my cleanup code? – Leo Lobeto May 29 '12 at 08:25

1 Answers1

3

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.

jd.
  • 10,678
  • 3
  • 46
  • 55
  • As it turns out you cannot capture signals in your Flask app if you run the default Werkzeug server (as it handles the signals internally, and then terminates your application). So the signal won't even reach your Flask app. Therefore `atexit` works in all cases, while the signal module won't. – mkisantal Mar 08 '21 at 14:05