Starting thread while running flask with debug

flask, multithreading, python

Solution

Werkzeug's reloading support has to fork to be able to reload the module correctly. As such your module is imported twice at least; more if you altered the module and it is reloaded.

You can switch this off the reloader with `use_reloader=False`:

app.run(use_reloader=False)

or you can start your thread in a `@app.before_first_request` decorated function:

t = Timer(1, once, ())

@app.before_first_request
def start_thread():
    t.start()

The `start_thread` function is now only executed when the first request comes in, not when importing.

Problem

When I try to start a thread in the same process as a flask app is running, two threads are started. So "once" will be printed twice. ``` from threading import Timer from flask import Flask app = Flask(__name__) app.config.update(dict( DEBUG = True )) def once(): print("once") t = Timer(1, once, ()) t.start() app.run() ``` This only happens when DEBUG is true. Anyone have any idea how to prevent this from happening when debugging?

Original source