How to implement threading with flask on heroku [duplicate]

自闭症网瘾萝莉.ら 提交于 2020-11-29 19:07:16

问题


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?


回答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



来源:https://stackoverflow.com/questions/63749430/how-to-implement-threading-with-flask-on-heroku

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!