0

I have the following code for testing running two threads with flask on heroku.

app.py

from flask import Flask, render_template
import threading
import time
import sys

app = Flask(__name__, static_url_path='')
test_result = 'failed'

@app.route('/')
def index():
    return 'Hello! Server is running'


@app.route('/thread-test')
def thread_test():
    global test_result
    return test_result


def thread_testy():
    time.sleep(10)
    global test_result
    test_result = 'passed'
    return


if __name__ == "__main__":
    threading.Thread(target=app.run).start()
    threading.Thread(target=thread_testy).start()

Procile

web: gunicorn app:app --log-file=-

This returns 'passed' locally, but 'failed' on heroku. Anyone have any ideas on how to get this test to work?

Jesse Reza Khorasanee
  • 3,140
  • 4
  • 36
  • 53

1 Answers1

1

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

Jesse Reza Khorasanee
  • 3,140
  • 4
  • 36
  • 53