Ok after lots of trial and error I finally found a solution to this. The key is to start your new thread @app.before_first_request
instead of in __main__
.
app.py
from flask import Flask, render_template
import threading
import time
import sys
app = Flask(__name__, static_url_path='')
test_result = 'failed'
@app.before_first_request
def execute_this():
threading.Thread(target=thread_testy).start()
@app.route('/')
def index():
return 'Hello! Server is running successfully'
@app.route('/thread-test')
def thread_test():
global test_result
return test_result
def thread_testy():
time.sleep(10)
print('Thread is printing to console')
sys.stdout.flush()
global test_result
test_result = 'passed'
return
def start_app():
threading.Thread(target=app.run).start()
if __name__ == "__main__":
start_app()
The above returns success at /thread-test after 10s