当客户端断开连接时,如何停止Django中的StreamingHttpResponse?

2024-06-02 08:02:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我的django服务器提供一个视频提要,作为jpeg流,一次一帧。在

看起来像这样:

class VideoCamera():
    def __init__(self):
        # code

    def get_frame(self):
        # code
        return frame

def gen(camera):
    while True:
        yield camera.get_frame()

def view_cam(request):
    return StreamingHttpResponse(gen(VideoCamera()), content_type="multipart/x-mixed-replace;boundary=frame")

这是一个直播的视频流。我需要在客户端断开连接时中断它,但是到目前为止,我还不知道如何检测客户端断开连接。在

我错过什么了吗?在

编辑:

为了消除与相机有关的任何问题,我做了以下操作:

^{pr2}$

并用curl -N http://localhost/my_app/view_cam/连接到我的视图。它将数字流化,当我用Ctrl+C停止curl时,生成器就会无限期地继续运行,而没有注意到客户机消失了。如果我再运行几次并停止curl,我的gen()函数的多个实例正在运行,这正是相机所发生的情况。在

编辑2:

这个项目使用Django频道。我注意到如果我在我的设置.py,上面的例子工作得很好。我不认为频道与这个问题有关,但显然,它是-不知何故。在

channels development server实际上在10秒后检测到断开连接(不像默认的django服务器那样立即检测),并显示以下内容:

Application instance call() running at /home/pi/paperless_clipboard/venv3/lib/python3.5/site-packages/channels/http.py:213> wait_for=._call_check_cancel() at /usr/lib/python3.5/asyncio/futures.py:452, Task._wakeup()]>> for connection took too long to shut down and was killed.

但是,尽管有消息说有东西被杀死,gen()继续运行,将数字打印到终端。在


Tags: djangopyself服务器viewgetreturndef
1条回答
网友
1楼 · 发布于 2024-06-02 08:02:18

你不能根据文件:

Performance considerations Django is designed for short-lived requests. Streaming responses will tie a worker process for the entire duration of the response. This may result in poor performance.

Generally speaking, you should perform expensive tasks outside of the request-response cycle, rather than resorting to a streamed response.

https://docs.djangoproject.com/en/2.1/ref/request-response/#streaminghttpresponse-objects

相关问题 更多 >