Flask 在端点上阻塞而不允许另一个端点调用

Flask blocking on endpoint without allowing another endpoint calls

我的烧瓶的一个端点 API 向直播流发出了一个很长的请求。这是代码示例:

@app.route('/stream')
def live_stream(sensor_id):
    stream = requests.get('stream_url', stream=True)
    return Response(stream_with_context(stream.iter_content(chunk_size=2048)),
                content_type=stream.headers['content-type'])

这条路线运行良好,直播顺利。但是,当我尝试向其他路由发出请求时,服务器似乎卡在了这个端点。

我正在使用 gevent WSGI 服务器:

 http_server = WSGIServer(('0.0.0.0', 5000), app).serve_forever()

我正在从 Flask 路由返回的模板发出请求。

如何向 API 发出并行请求而不会卡在上面?

我从来没有用过gevent,但如果我理解正确的话,它有一个单线程事件循环(像asyncio)。但我的理解可能是错误的。

看看这个答案

When you have a piece of python code that takes a long time to run (for seconds) and does not cause switching of greenlets, all other greenlets / gevent jobs will 'starve' and have no computation time and it will look like your application 'hangs'.

我建议执行以下操作之一:

  • 或者,运行 您在线程 WSGI 服务器中的 Web 应用程序
  • 或者,研究 gevent 是否有一个网络客户端,你可以使用它来代替基于 greelets
  • requests
  • 或者,运行线程工具中代码的阻塞部分
  • 或者,调用 from gevent import monkey; monkey.patch_all() 作为服务器代码中的第一件事,看看这是否会使 requests 表现得非阻塞。

您可以通过以下步骤查看:

  1. 确保你的代码在第一行是 monkey patched(否则如果某些模块没有打补丁并且做一些 I/O 您的应用程序将阻止的操作。我记得gevent里面有一个API可以帮忙查一下monkey.is_module_patched('request'));
  2. 确保您没有在执行某些 CPU 有界任务(CPU 有界代码会阻止您的代码);

希望对您有所帮助!