Como implementar threading com flask no heroku [duplicado]
Sep 04 2020
Eu tenho o seguinte código para testar a execução de dois threads com flask no 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=-
Isso retorna 'aprovado' localmente, mas 'falhou' no heroku. Alguém tem alguma ideia de como fazer esse teste funcionar?
Respostas
JesseRezaKhorasanee Sep 05 2020 at 00:52
Ok, depois de muitas tentativas e erros, finalmente encontrei uma solução para isso. A chave é iniciar seu novo tópico em @app.before_first_requestvez de no __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()
O item acima retorna sucesso em / thread-test após 10s
O que significa um erro “Não é possível encontrar o símbolo” ou “Não é possível resolver o símbolo”?
Christopher Nolan uma vez se arrependeu de ter lido o 'roteiro de Pulp Fiction' de Quentin Tarantino