Last active
March 6, 2023 07:27
-
-
Save gmolveau/10c80785d499c2e2d4c447343a624664 to your computer and use it in GitHub Desktop.
run a flask application in a separate thread
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# please use python3 and flask > 1.0 | |
# run this with : python3 flask_separate_thread.py | |
# https://web.archive.org/web/20210329135424/https://pymotw.com/3/threading/ | |
# https://web.archive.org/web/20210329135553/https://eli.thegreenplace.net/2011/08/22/how-not-to-set-a-timeout-on-a-computation-in-python | |
import time | |
import threading | |
from flask import Flask | |
app = Flask(__name__) | |
@app.route('/') | |
def hello_world(): | |
return 'Hello, World!' | |
def web(): | |
app.run(debug=True, use_reloader=False, host='0.0.0.0', port=5000) | |
def usb(arg1, arg2): | |
print(f"this is how to pass arguments to a thread function - {arg1} - {arg2}") | |
while True: | |
print("waiting for USB") | |
time.sleep(2) | |
if __name__ == '__main__': | |
threading.Thread(target=web, daemon=True).start() | |
threading.Thread(target=usb, daemon=True).start() | |
while True: | |
time.sleep(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Well, I separated my code into files, but I will explain each one. I work with Blueprints for my route functions.
Work with apache-XAMPP as webserver and Waitress as Python WSGI server.
First, I used a project structure that used this tutorial (but it is in Spanish). My project structure is:
The
entry_point.py
has the instance of the Flask application that calls thegenerate_app()
function onapp/__init__.py
:The
app/__init__.py
has the function that generates the Flask application. Any other thread should be initiated here:In the
app/updater.py
file, should be written the function that runs in the other thread, that it will be called bygenerate_app()
inapp/__init__.py
:Finally, it will be started with:
flask run
command orwaitress-serve --listen=127.0.0.1:5000 entry_point:application
command. The Waitress command is for production.Note: The debug mode may duplicate the Flask app