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