Channels cannot be used with StreamingHttpResponse

When using Channels, StreamingHttpResponse is blocked.

def gen():
    while True:
        image = cv2.imread('a.jpg')
        ret, jpeg = cv2.imencode('.jpg', image)
        img_frame = jpeg.tobytes()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + img_frame + b'\r\n\r\n')

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

But without ‘while true’, the request is passed

You haven’t really provided any details or context about what you’re trying to achieve, but it appears to me that what you’re trying to do here doesn’t make a whole lot of sense.

Channels and HttpResponses are two completely separate things.

A StreamingHttpResponse is used for returning data as the response to your page request.

Channels are established and used after a page has been received and rendered.

You don’t send HttpResponses through channels.

If you provide more details about what you’re trying to do, we might be able to assist you.

1 Like

Not channels.Use ASGI to deploy Django,StreamingHttpResponse cannot be accessed.
If I use ‘while True’,the request is always pending.

So you’re saying that this exact code works if you run it under a wsgi container?

Wsgi is fine, but ASGi is not

same +1 “While True” always wait to infinity.

Async support for StreamingHttpResponse was only added in Django 4.2.

Assuming you’re using that, please open an issue on the Channels repo with a full reproduce. Django’s 4.2’s ASGIHandler streams the response into ASGI messages, so this should work in theory — but without a concrete example it’s not possible to say what’s going on.

Hi Carl,

  1. I’m working on Django 4.2 with daphne, channels, opencv-python
    2.I’ve been following this issue for a long time: Daphne does not stream · Issue #413 · django/daphne · GitHub
  • This my class. its captured the my webcam and stream to frontend.

Ekran Resmi 2023-05-29 18.21.40

  • My View

  • urls.py
path("camera_feed/", video_feed, name="video_feed"),
  • on tamplate (HTML)
<div>
    <img src="{% url 'video_feed' %}" alt="">
</div>
  • This my solution working good. not bad. But if i try the change for loop to while loop and remove the asyncio.sleep:
async def get_frame(self):
       while True:
            if self.video.isOpened():
                success, frame = self.video.read()
                ret, jpeg = cv2.imencode('.jpg',frame)
                jpeg_bytes = jpeg.tobytes()
                yield (b'--frame\r\n'
                    b'Content-Type: image/jpeg\r\n\r\n' + jpeg_bytes + b'\r\n\r\n')
            else:
                yield b'a'
  • Now get_frame not a aysnc generating frame. İts waiting the loop finish and while condition is True. Thats why request is always pending. to infinity.

Ekran Resmi 2023-05-29 18.48.25
Ekran Resmi 2023-05-29 18.47.36