ob_flush() equivalent in Python

I am writing an AJAX script call function in python which will return a series of status updates which I want to read in real-time. In PHP it’s possible by making use of ob_flush() and getting the output immediately and my AJAX call can read it as and when it comes. I’m looking for the equivalent in Python/Django.

Might using StreamingHttpResponse with an ASGI server get you where you want to be?

from django.http import StreamingHttpResponse
import time

def stream_status_updates(request):
    def generate_status_updates():
        for i in range(10):
            yield f"Status update {i}\n"
            time.sleep(1)

    response = StreamingHttpResponse(generate_status_updates(), content_type="text/plain")
    response['Cache-Control'] = 'no-cache'
    return response
1 Like