Quart无限/无限流响应

时间:2018-10-30 22:05:20

标签: python-3.x python-asyncio quart

我正在尝试基于an old blog post创建一个服务器(宽松地)以使用Quart流式传输视频。

要将视频流传输到客户端,似乎我需要做的就是拥有一条返回帧生成器的路由。但是,实际上,这样做会导致不断出现socket.send() raised exception重复消息,并在客户端上显示损坏的图像。此后,服务器似乎不再响应其他请求。

利用原始帖子的更多灵感,我尝试返回Response(使用return Response(generator, mimetype="multipart/x-mixed-replace; boundary=frame")。)实际上确实在客户端上显示视频,但是一旦他们断开连接(关闭选项卡,导航转到另一页等),服务器再次开始向socket.send() raised exception发送垃圾邮件,并且不再响应其他请求。

我的代码在下面。

# in app.py
from camera_opencv import Camera
import os
from quart import (
    Quart,
    render_template,
    Response,
    send_from_directory,
)

app = Quart(__name__)

async def gen(c: Camera):
    for frame in c.frames():
        # d_frame = cv_processing.draw_debugs_jpegs(c.get_frame()[1])
        yield (b"--frame\r\nContent-Type: image/jpeg\r\n\r\n" + frame[0] + b"\r\n")


c_gen = gen(Camera(0))


@app.route("/video_feed")
async def feed():
    """Streaming route (img src)"""
    # return c_gen
    return Response(c_gen, mimetype="multipart/x-mixed-replace; boundary=frame")

# in camera_opencv.py
from asyncio import Event
import cv2

class Camera:
    last_frame = []

    def __init__(self, source: int):
        self.video_source = source
        self.cv2_cam = cv2.VideoCapture(self.video_source)
        self.event = Event()

    def set_video_source(self, source):
        self.video_source = source
        self.cv2_cam = cv2.VideoCapture(self.video_source)

    async def get_frame(self):
        await self.event.wait()
        self.event.clear()
        return Camera.last_frame

    def frames(self):
        if not self.cv2_cam.isOpened():
            raise RuntimeError("Could not start camera.")

        while True:
            # read current frame
            _, img = self.cv2_cam.read()

            # encode as a jpeg image and return it
            Camera.last_frame = [cv2.imencode(".jpg", img)[1].tobytes(), img]
            self.event.set()
            yield Camera.last_frame
        self.cv2_cam.release()

1 个答案:

答案 0 :(得分:0)

最初是an issue with Quart itself.

在对Quart和Hypercorn进行了一系列错误修复之后,所发布的代码按预期运行(自2018年11月13日开始)。