how to respose line by line in django API
To respond line by line in a Django API, you can use the StreamingHttpResponse class provided by Django. Here's an example:
from django.http import StreamingHttpResponse
def stream_response(request):
def stream():
yield "First line\n"
yield "Second line\n"
yield "Third line\n"
response = StreamingHttpResponse(stream(), content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename="lines.txt"'
return response
In this example, we define a function stream() that yields each line of text as a separate string, separated by newline characters. We then create a StreamingHttpResponse object that uses stream() as its source of content. Finally, we set the Content-Disposition header to suggest that the response should be downloaded as a file named lines.txt.
When a client makes a request to this view, they will receive a response with the lines of text streamed to them one at a time, with each line separated by a newline character.
原文地址: https://www.cveoy.top/t/topic/0mP 著作权归作者所有。请勿转载和采集!