简体   繁体   English

Django StreamingHttpResponse 的问题

[英]Problem with Django StreamingHttpResponse

I'm having a problem with Django response class StreamingHttpResponse.我遇到 Django 响应 class StreamingHttpResponse 的问题。 When I return a generator as response using StreamingHttpResponse and make a request I excepted to retrieve each data block one by one, instead of that i retrieve the full data at once when the generator loop has finished.当我使用 StreamingHttpResponse 返回生成器作为响应并发出请求时,我例外地逐个检索每个数据块,而不是在生成器循环完成后立即检索完整数据。

My Django View:我的 Django 查看:

def gen_message(msg):
    return '\ndata: {}\n\n'.format(msg)


def iterator():
    for i in range(100):
        yield gen_message('iteration ' + str(i))
        print(i)
        time.sleep(0.1)

class test_stream(APIView):
    def post(self, request):
        stream = iterator()
        response = StreamingHttpResponse(stream, status=200, content_type='text/event-stream')
        response['Cache-Control'] = 'no-cache'
        return response

And I make the request like that:我这样提出请求:

r = requests.post('https://******/test_stream/', stream=True)


for line in r.iter_lines():

    if line:
        decoded_line = line.decode('utf-8')
        print(decoded_line)

When I see the output of the Django server I can see the print every 0.1 seconds.当我看到 Django 服务器的 output 时,我可以每 0.1 秒看到一次打印。 But the response in the second code only shows when the for loop is finished.但是第二个代码中的响应仅在 for 循环完成时显示。 Am I misunderstanding the StreamingHttpResponse class or the request class or is there another problem?我误解了 StreamingHttpResponse class 或请求 class 还是有其他问题? Thanks:)谢谢:)

You will need to ensure that there is no middleware or webserver in between that first "buffers" the response.您将需要确保在第一个“缓冲”响应之间没有中间件或网络服务器。

In Nginx that is possible if the proxy_buffering setting is turned on.在 Nginx 中,如果proxy_buffering设置打开,这是可能的。 You will thus need to disable this with:因此,您需要通过以下方式禁用它:

proxy_buffering off;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM