Hook when Flask restarts in debug mode Hook when Flask restarts in debug mode flask flask

Hook when Flask restarts in debug mode


I think I have found a way to handle the issue.The issue comes from the first werkzeug reload saying which watcher for file it will used, logging something like:

* Restarting with inotify reloader"

The reload is done with a subprocess.call, so we have 2 different Python interpreters running at the same time!

On the other reloads (on file changed), there is a good advantage, the subprocess is killed before launching a new one, quite brutal but doing the job:

Here how it is done on werkzeug:

        sig = getattr(signal, "SIGKILL", signal.SIGTERM)        # reloader active        if is_running_from_reloader():            os.kill(os.getpid(), sig)

My solution is, when I am using werkzeug (when app.debug is true in my case) and only do my background thread init on the reloaded subprocess.To know your are in the subprocess werkzeug provides is_running_from_reloader function

into app/__init__.py:

if not app.debug or app.debug and werkzeug.serving.is_running_from_reloader():    # do what you want to do at start up

and somewhere else, for me into a class, do cleaning at exit (when process is killed)

class MyClass:    @classmethod    def cleanOnExit(cls):        # do here your cleaningimport atexit ; atexit.register(MyClass.cleanOnExit)