Sometimes, we want to start a Python Flask application in separate thread.
In this article, we’ll look at how to start a Python Flask application in separate thread.
How to start a Python Flask application in separate thread?
To start a Python Flask application in separate thread, we set the use_reloader to False when we call app.run.
And then we create a Thread instance with the Flask app by setting the function that calls app.run as the value of the target argument.
For instance, we write
from flask import Flask
import threading
data = 'hello'
host_name = "0.0.0.0"
port = 23336
app = Flask(__name__)
@app.route("/")
def main():
return data
if __name__ == "__main__":
threading.Thread(target=lambda: app.run(host=host_name, port=port, debug=True, use_reloader=False)).start()
to create a threading.Thread instance with the target set to a function that calls app.run with use_reloader set to False to start the app in a separate thread.
Conclusion
To start a Python Flask application in separate thread, we set the use_reloader to False when we call app.run.
And then we create a Thread instance with the Flask app by setting the function that calls app.run as the value of the target argument.