对不起我的英语水平。我想制作一个流式传输视频并运行多种功能的网页。我正在使用 python 和 flask 服务器。但是,有些问题我无法单独解决。我有源代码。这几乎是完美的。
源代码。
import time
from flask import Flask, render_template, Response
from camera import Camera
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
def gen(camera):
while True:
frame = camera.get_frame()
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():
return Response(gen(Camera()),
mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/test')
def test():
return time.time()
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True
和模板
<html>
<head>
<title>Video Streaming Demonstration</title>
</head>
<body>
<h1>Video Streaming Demonstration</h1>
<img src="{{ url_for('video_feed') }}">
</body>
</html>
在源代码中,名为 gen() 的函数使用了“yield”。所以,它永远不会结束。它占用所有资源。我想在视频流式传输时运行另一个功能,如“测试”功能。
最佳答案
视频流需要与客户端的永久连接。如果您使用 Flask 开发 Web 服务器执行此操作,那么您将无法处理任何其他请求,因为默认情况下该服务器一次处理一个连接。
如果您想同时处理多个连接,您有两种选择。最简单(但不是很健壮或高效)是以线程模式运行开发服务器(只需在 app.run()
调用中添加 threaded=True
)。这将为传入请求生成新线程。更适合生产的解决方案是切换到不同的 Web 服务器。例如,使用 gunicorn,您可以控制启动多少个工作进程。为了获得更大的灵 active ,诸如 gevent 之类的服务器可以处理真正大量的并发客户端请求。
关于python - 使用带 raspi 相机的 flask 进行视频流传输,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31069318/