Start a flask application in separate thread Start a flask application in separate thread flask flask

Start a flask application in separate thread


You're running Flask in debug mode, which enables the reloader (reloads the Flask server when your code changes).

Flask can run just fine in a separate thread, but the reloader expects to run in the main thread.


To solve your issue, you should either disable debug (app.debug = False), or disable the reloader (app.use_reloader=False).

Those can also be passed as arguments to app.run: app.run(debug=True, use_reloader=False).


Updated answer for Python 3 that's a bit simpler:

from flask import Flask                                                         import threadingdata = 'foo'host_name = "0.0.0.0"port = 23336app = Flask(__name__)@app.route("/")def main():    return dataif __name__ == "__main__":    threading.Thread(target=lambda: app.run(host=host_name, port=port, debug=True, use_reloader=False)).start()


If you are looking for accessing iPython terminal in Flaskrun your application in a separate thread. Try this example:

from flask import Flask                                                         import threaddata = 'foo'app = Flask(__name__)@app.route("/")def main():    return datadef flaskThread():    app.run()if __name__ == "__main__":    thread.start_new_thread(flaskThread, ())

(Run this file in iPython)