StreamingHttpResponse和HttpResponse

在修改以前的文件下载功能时,发现一个文件有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/

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值