StreamingHttpResponse not working with ASGI but work fine with WSGI

Viewed 270

I'm trying to use channels for some WebSockets-related stuff, but it keeps loading and not showing any streaming response when I reload my web page. Here is my code which works fine with this setting:

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

And here is my 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")

Here is my code for generate_frames and VideoCamera:

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')

0 Answers
Related