python - 带有 socketIO 和 eventlet 的 Flask Response 会导致响应丢失?
问题描述
我正在试验 Miguel 关于使用烧瓶流式传输 jpg 图像的教程中的代码。第 1部分 第 2 部分
我试图将 socketIO 添加到示例中。但我发现即使使用猴子补丁也会导致严重滞后。我将问题归结为下面看到的这个简短示例。如果我启动socketio
实例,那么我会在终端中看到生成器以固定的时间间隔提供连续的帧,但在浏览器中只显示大约每秒的图像。如果我使用app.run(...)
,那么一切正常。使用socketio
withasync_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)
解决方案
我不确定问题是什么,但它似乎与使用 eventlet Web 服务器有关。切换到 Gunicorn 附带的 eventlet worker 似乎可以解决问题。
我首先安装了 Gunicorn:
pip install gunicorn
然后按如下方式启动您的应用程序:
gunicorn -b :5000 -k eventlet app_experiment:app
推荐阅读
- javascript - 将孩子从一个父母移动到另一个父母时的翻译动画
- java - 线程的 getId() 是否提供有保证的序列?
- google-chrome - 关闭网络浏览器中的重复选项卡
- powerbi - 刷新数据时找不到表中的列
- web-applications - 数据库是否跨区域部署(Web 应用程序)?
- swift - 将 macOS 应用程序添加到隐私系统偏好设置中的可访问性列表
- laravel - 在 null laravel crud 上调用成员函数 getClientOriginalExtension()?
- go - RPC 响应不正确
- arrays - 尝试在 React 中映射子对象时出现未定义错误
- java - 如何在 Spring JPA @Query 中获取完全匹配的记录