1

Is there a way to call a function when Flask is killed? I want to run some server teardown tasks to gracefully stop my application.

Also, is there a similar analog for Flask startup? I'm currently putting all my startup code in the same file that calls app = Flask(__name__) - not sure if that's good practice.

Thanks!

Carpetfizz
  • 8,707
  • 22
  • 85
  • 146
  • Not sure what your setup is but would this work? http://flask.pocoo.org/snippets/67/ – ltd9938 Jul 12 '18 at 14:49
  • @ltd9938 interesting, does that ‘/shutdown’ route get called automatically? Doesn’t make sense to have a separate request to kill the server – Carpetfizz Jul 12 '18 at 14:51
  • 2
    you should not be serving flask with `app.run()` and when using a proper serving mechanism there is no such thing as "shutdown" (well at least not how you talk about it here) ... but if you really want to you can use `atexit.register` or you can `try: app.run() finally: cleanup()` – Joran Beasley Jul 12 '18 at 14:53
  • @JoranBeasley node.js does this actually https://stackoverflow.com/a/14032965 – Carpetfizz Jul 12 '18 at 14:55
  • @Carpetfizz I can imagine if you are using a node backend it has a mechanism for atexit just like python .... but you should not be using the wekzeug backend that comes with flask and django and all the others as its just not very robust... you use something like nginx or apache to serve your pages ... as such you would need to use something like supervisor or upstart jobs to register a job with the operating system and give it startup rules that fire when you want them too ... but regardless you have not given enough info for anyone to really help you ... i guess try `atexit.register` ... – Joran Beasley Jul 12 '18 at 15:01

0 Answers0