【问题标题】:Running multiple threads from Flask app on Heroku, with Gunicorn and gevent使用 Gunicorn 和 gevent 从 Heroku 上的 Flask 应用程序运行多个线程
【发布时间】:2021-11-03 08:06:13
【问题描述】:

我有一个 Flask 应用程序,在提交表单时,它需要启动一个新线程。我正在使用 Gunicorn 在免费的 Heroku dyno 上运行该应用程序,每次我调用 threading.Thread().start()gevent.threading.Thread().start() 时,请求都会挂起并最终超时。我在下面直接放了 Heroku 日志的 sn-p,但是,基本上,一旦工人死亡,另一个似乎拿起并启动线程没问题,但这最终意味着表单提交需要很长时间并且通常需要刷新。

(Heroku 日志): 2021-09-06T07:37:56.372718+00:00 heroku[路由器]: at=info method=POST path="/form## Heading ##" host=.herokuapp.com request_id=2fcceff4-70d5-4629-bd06 -0df682c9a0a9 fwd="152.3.43.49" dyno=web.1 连接=0ms 服务=29609ms 状态=200 字节=4485 协议=http 2021-09-06T07:37:56.372291+00:00 app[web.1]: [2021-09-06 07:37:56 +0000] [4] [CRITICAL] 工作人员超时(pid:32)

到目前为止我已经尝试过:

  • 同时使用geventthreading 线程。
  • 使用geventeventlet 运行我的Procfile,将--threads 和--worker-connections 选项设置为100,正如this 帖子所建议的那样。
  • 使用 uWSGI 运行

简化的复制是这样的:

Procfile: web: gunicorn -k gevent --worker-connections 100 app:app

app.py

app = Flask(__name__)

@app.route("/form", methods=["POST"])
def form():
    t = threading.Thread(target=func, args=(request.form["code"],))
    t.setDaemon(true)
    t.start()
    return render_template("index.html")

def func(code):
    while True:
        # do stuff (loop will not terminate)

【问题讨论】:

    标签: python multithreading flask heroku gunicorn


    【解决方案1】:

    对于关心的人,我找到了一个适合我的解决方案,使用 eventleteventlet.spawn

    Procfileweb: gunicorn --worker-class eventlet -w 1 app:app

    app.py

    import eventlet
    eventlet.monkey_patch()
    
    app = Flask(__name__)
    
    @app.route("/form", methods=["POST"])
    def form():
        eventlet.spawn(func,request.form["code"]) # the solution I found
        return render_template("index.html")
    
    def func(code):
        while True:
            # do stuff (loop will not terminate)
    
    

    【讨论】:

      猜你喜欢
      • 2012-11-26
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      • 2015-01-05
      • 2022-01-18
      • 2020-02-28
      • 1970-01-01
      相关资源
      最近更新 更多