Python Flask shutdown event handler Python Flask shutdown event handler flask flask

Python Flask shutdown event handler


There is no app.stop() if that is what you are looking for, however using module atexit you can do something similar:

https://docs.python.org/2/library/atexit.html

Consider this:

import atexit#defining function to run on shutdowndef close_running_threads():    for thread in the_threads:        thread.join()    print "Threads complete, ready to finish"#Register the function to be called on exitatexit.register(close_running_threads)#start your processapp.run()

Also of note-atexit will not be called if you force your server down using Ctrl-C.

For that there is another module- signal.

https://docs.python.org/2/library/signal.html


from flask import requestBASE_URL = "http://127.0.0.1:5000"SHUTDOWN = "/shutdown"def shutdown_server():    func = request.environ.get('werkzeug.server.shutdown')    if func is None:        raise RuntimeError('Not running with the Werkzeug Server')    func()@app.route(SHUTDOWN, methods=['POST'])def shutdown():    shutdown_server()    return 'Server shutting down...'

There seems to be a way mentioned here :-http://web.archive.org/web/20190706125149/http://flask.pocoo.org/snippets/67