【问题标题】:How to implement threading with flask on heroku [duplicate]如何在heroku上使用flask实现线程[重复]
【发布时间】:2020-12-24 05:08:21
【问题描述】:

我有以下代码用于测试在 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()

程序

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

这在本地返回“通过”,但在 Heroku 上返回“失败”。有人对如何让这个测试起作用有任何想法吗?

【问题讨论】:

    标签: python multithreading flask heroku


    【解决方案1】:

    好的,经过大量的反复试验,我终于找到了解决方案。关键是在@app.before_first_request 而不是__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()
    

    以上在/thread-test 10s 后返回成功

    【讨论】:

    • 我不知道为什么,但这不再有效。
    猜你喜欢
    • 2022-01-17
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    • 2018-10-06
    • 2018-11-15
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多