Come implementare il threading con flask su heroku [duplicato]

Sep 04 2020

Ho il seguente codice per testare l'esecuzione di due thread con flask su 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=-

Questo restituisce "passato" localmente, ma "non riuscito" su heroku. Qualcuno ha qualche idea su come far funzionare questo test?

Risposte

JesseRezaKhorasanee Sep 05 2020 at 00:52

Ok, dopo molti tentativi ed errori ho finalmente trovato una soluzione a questo. La chiave è iniziare il tuo nuovo thread @app.before_first_requestinvece che 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()

Quanto sopra restituisce il successo in / thread-test dopo 10s