0

What is the simplest way to reliably save data to a file when flask app.run() stops/crashes?

try:
   app.run()
except Exception as e:
   #<cleanup and save>

Does not work for sigint/ctrl+c etc they must be try/excepted in app.run()

signal.signal(signal.SIGINT, signal_handler)
app.run()
signal.pause()

works for ctrl+c (but not always)

@app.errorhandler(Exception)
def save_on_exit(error):
    # <cleanup and save>
    return response

works on error in views.

Is there a solution that just writes to the file on exit, or do I need all 3 of those?

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
MortenB
  • 2,749
  • 1
  • 31
  • 35
  • See `atexit` or `signal` standard libraries. – Fine Jun 07 '18 at 11:51
  • 2
    Short answer: there's no __reliable__ way to do anything "when an app crashes" - for example you cannot expect to allocate any memory after a MemoryError or to write to disk if your filesystem is dead or full (and those are only two examples). – bruno desthuilliers Jun 07 '18 at 11:57
  • I tried signal it caches ctrl+c but not reliably, atexit does not catch ctrl+c but it works for the rest. – MortenB Jun 07 '18 at 12:35
  • This is related to flask app.run() – MortenB Jun 07 '18 at 13:11

0 Answers0