首页 > 解决方案 > 带有 socketIO 和 eventlet 的 Flask Response 会导致响应丢失?

问题描述

我正在试验 Miguel 关于使用烧瓶流式传输 jpg 图像的教程中的代码。第 1部分 第 2 部分

我试图将 socketIO 添加到示例中。但我发现即使使用猴子补丁也会导致严重滞后。我将问题归结为下面看到的这个简短示例。如果我启动socketio实例,那么我会在终端中看到生成器以固定的时间间隔提供连续的帧,但在浏览器中只显示大约每秒的图像。如果我使用app.run(...),那么一切正常。使用socketiowithasync_mode="threading"还可以修复流式传输。

我错过了什么?

模板/index.html

<html>
  <head>
    <title>Video Streaming Demonstration</title>
  </head>
  <body>
    <h1>Video Streaming Demonstration</h1>
    <img src="{{ url_for('video_feed') }}">
  </body>
</html>

app_experient.py

import eventlet
eventlet.monkey_patch()

from importlib import import_module
import os
from flask import Flask, render_template, Response

import time
print("is_monkey_patched(time):", eventlet.patcher.is_monkey_patched(time))

from flask_socketio import SocketIO

app = Flask(__name__)
socketio = SocketIO(app)#, async_mode="threading")


@app.route('/')
def index():
    """Video streaming home page."""
    return render_template('index.html')


def gen():
    """Video streaming generator function."""
    imgs = [open(f + '.jpg', 'rb').read() for f in ['1', '2', '3', '4', '5', '6', '7']]

    while True:
        time.sleep(1)
        i = int(time.time()) % 7
        frame = imgs[i]
        print("gen yielding", i)
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')


@app.route('/video_feed')
def video_feed():
    """Video streaming route. Put this in the src attribute of an img tag."""
    return Response(gen(),
                    mimetype='multipart/x-mixed-replace; boundary=frame')


if __name__ == '__main__':
    # app.run(host='0.0.0.0', threaded=True)#, debug=True)
    socketio.run(app, host='0.0.0.0')#, debug=True)

标签: pythonflaskflask-socketio

解决方案


我不确定问题是什么,但它似乎与使用 eventlet Web 服务器有关。切换到 Gunicorn 附带的 eventlet worker 似乎可以解决问题。

我首先安装了 Gunicorn:

pip install gunicorn

然后按如下方式启动您的应用程序:

gunicorn -b :5000 -k eventlet app_experiment:app

推荐阅读