简体   繁体   English

使用 Gunicorn 和 Gevent 运行 Flask 时如何使用请求发出非阻塞请求

[英]how to make a non-blocking request with requests when running Flask with Gunicorn and Gevent

My Flask application will receive a request, do some processing, the processiong takes long time.我的 Flask 应用程序会收到一个请求,做一些处理,处理需要很长时间。 Running Gunicorn with Gevent will allow it to handle many of these slow requests at the same time.使用 Gevent 运行 Gunicorn 将允许它同时处理许多这些缓慢的请求。 I konw when my application process this request, it also can process other requests, But my purpose is that in this request it can response client quickly and still process image download on background。 How can I modify the example below so that the view is non-blocking?我知道当我的应用程序处理这个请求时,它也可以处理其他请求,但我的目的是在这个请求中它可以快速响应客户端并且仍然在后台处理图像下载。我如何修改下面的例子,使视图是非-阻塞?

@app.route('/do', methods = ['POST'])
def do():
    # here download many picture, it will tasks long time, and block。
    return 'ok'

Flask + gevent isn't the right tool for this. Flask + gevent 不是正确的工具。 Gevent uses monkey patching to run regular code on the event loop- but in the process, you don't have the ability to run regular event loop stuff (like scheduling an async task). Gevent 使用猴子补丁在事件循环上运行常规代码 - 但在此过程中,您无法运行常规事件循环内容(例如调度异步任务)。 I am not a gevent expert (so maybe there is a technique I am not aware of), but I don't think so.我不是 gevent 专家(所以也许有一种我不知道的技术),但我不这么认为。

To accomplish this, I would do one of two things.为了实现这一点,我会做两件事之一。

  1. Set up an async task system.设置异步任务系统。 I have used celery a ton, but there are other alternatives.我用了一吨芹菜,但还有其他的选择。 The downside of this is you usually need another piece of infrastructure- Redis, rabbitmq, something like that.这样做的缺点是你通常需要另一块基础设施——Redis、rabbitmq 之类的东西。 It really is the best solution though.不过,这确实是最好的解决方案。

  2. Use an explicitly async web framework.使用显式异步 Web 框架。 I use Sanic for this.我为此使用 Sanic。 It lets you schedule coroutines directly from a view so that they can continue to run even after the view coroutine has completed.它让您可以直接从视图中调度协程,以便即使在视图协程完成后它们也可以继续运行。 This means that ALL your code has to be async though, which is a learning curve.这意味着您的所有代码都必须是异步的,这是一个学习曲线。

There is a less good solution to use threading or multiprocessing to start your work and just not have anything monitoring it to do cleanup.使用线程或多处理来开始您的工作并且没有任何监控它来进行清理是一个不太好的解决方案。 Finally, uwsgi has some stuff built in for background tasks, though I haven't tried it.最后,uwsgi 为后台任务内置了一些东西,尽管我还没有尝试过。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM