class MyThreadthreadingThread def __init__self super__init__ selfcontent = selfget_content def get_contentself # Your code to generate the content goes here re
The main issue with this code is that the content of the response is not being streamed properly. To fix this, we need to modify the MyThread class to actually stream the content:
import threading
from django.http import StreamingHttpResponse
from rest_framework.views import APIView
class MyThread(threading.Thread):
def __init__(self):
super().__init__()
self.content_generator = self.get_content_generator()
def get_content_generator(self):
# Your code to generate the content goes here
yield b"Hello "
yield b"world"
def run(self):
pass # Nothing to do here, since we're using a generator
class MyView(APIView):
def get(self, request):
thread = MyThread()
thread.start()
return StreamingHttpResponse(content=thread.content_generator, content_type="text/plain")
Here, we've modified the MyThread class to create a generator for the content instead of a static byte string. We then modified the run method to do nothing, since we're using the generator instead of a pre-generated byte string.
In the MyView class, we now return the content_generator instead of content, and we set the content type to "text/plain". This should allow the client to start receiving chunks of the response as they become available, instead of waiting for the entire response to be generated before sending anything.
原文地址: http://www.cveoy.top/t/topic/bluh 著作权归作者所有。请勿转载和采集!