Ask Your Question

Revision history [back]

You can use Python/Django to receive streaming responses and collect them all into a single StreamingHttpResponse using the following steps:

  1. Define a view function in your Django project that takes the request and returns a StreamingHttpResponse.
from django.http import StreamingHttpResponse

def my_view(request):
    # Your view logic here
    response = StreamingHttpResponse(streaming_content=...)
    return response
  1. In the response object, pass a generator or an iterator that returns the streaming content. This will send chunks of data to the client as soon as they become available.
def my_generator():
    # Your generator logic here
    yield b'Chunk 1 of data'
    yield b'Chunk 2 of data'
    yield b'Chunk 3 of data'

response = StreamingHttpResponse(streaming_content=my_generator())
  1. Create a list to collect the generator/iterator objects for all the responses you want to combine. You can use a loop to call the view function and add the generator/iterator object to the list.
responses = []
for i in range(10):
    # Your view logic here
    response = StreamingHttpResponse(streaming_content=...)
    responses.append(response)
  1. Define a new generator/iterator that loops over all the generator/iterator objects in the list, yielding their chunks of data one by one.
def combined_generator(responses):
    for response in responses:
        for chunk in response.streaming_content:
            yield chunk

response = StreamingHttpResponse(streaming_content=combined_generator(responses))
  1. Return the new generator/iterator object in a new StreamingHttpResponse object to send all the chunks of data to the client as a single stream.
response = StreamingHttpResponse(streaming_content=combined_generator(responses))
return response