StreamingHttpResponse和HttpResponse

来源:互联网 发布:安卓电子白板书写软件 编辑:程序博客网 时间:2024/06/06 01:45

在修改以前的文件下载功能时,发现一个文件有5G,用HttpResponse实现时,服务器返回502错误,查看nginx log时,发现nginx log记录的是: upstream prematurely closed connection while reading response header from upstream。应该是nginx服务器从上游获取数据时超时了。查了很多办法,修改了nginx的配置,但是仍然超时。绝望之下,查了一下Django的文档,发现了StreamingHttpResponse,试了一下效率提高了很多。后来仔细查了一下发现HttpResponse在使用文件迭代器时:

 HttpResponse will consume the iterator immediately, store its content as a string, and discard it.
HttpResponse会直接使用迭代器对象,将迭代器对象的内容存储城字符串,然后返回给客户端,同时释放内存。可以当文件变大看出这是一个非常耗费时间和内存的过程。

而StreamingHttpResponse是将文件内容进行流式传输,StreamingHttpResponse在官方文档的解释是:

The StreamingHttpResponse class is used to stream a response from Django to the browser. You might want to do this if generating the response takes too long or uses too much memory.
这是一种非常省时省内存的方法。但是因为StreamingHttpResponse的文件传输过程持续在整个response的过程中,所以这有可能会降低服务器的性能。

参考文档:https://docs.djangoproject.com/en/1.10/ref/request-response/

0 0
原创粉丝点击