首页 > 解决方案 > StreamingHttpResponse 不适用于 ASGI,但可以正常使用 WSGI

问题描述

我正在尝试使用channels一些与 WebSockets 相关的东西,但是当我重新加载我的网页时,它会一直加载并且不显示任何流式响应。这是我的代码,适用于此设置:

# settings.py
# WSGI_APPLICATION = 'main.wsgi.application' # work fine
ASGI_APPLICATION = "main.asgi.application"  # not working

这是我的views.py

@gzip.gzip_page  # for performance
def video_stream(request: HttpRequest):
    video = VideoContainer.objects.last()
    video_path = video.file.path
    return StreamingHttpResponse(generate_frames(VideoCamera(video_path)),
                                 content_type="multipart/x-mixed-replace;boundary=frame")

这是我的代码generate_framesVideoCamera

import cv2


class VideoCamera:
    def __init__(self, video_path: str):
        self.video = cv2.VideoCapture(video_path)

    def __del__(self):
        self.video.release()

    def get_frame(self):
        while (self.video.isOpened()):
            img = self.video.read()[1]

            # because web-page looking for image/jpeg content type
            jpeg = cv2.imencode(".jpg", img)[1]
            return jpeg.tobytes()  # we stream it in byte form for frontend


def generate_frames(camera) -> bytes:
    while True:
        frame = camera.get_frame()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')

标签: djangodjango-viewsdjango-channelsdjango-wsgi

解决方案


推荐阅读