Django的视图流式响应机制

栏目: Python · 发布时间: 8年前

内容简介:Django的视图流式响应机制

Django的视图流式响应机制

Django的响应类型:一次性响应和流式响应。

一次性响应,顾名思义,将响应内容一次性反馈给用户。HttpResponse类及子类和JsonResponse类属于一次性响应。

流式响应,顾名思义,将响应内容以流的形式逐步的反馈给用户。StreamingHttpResponse类和FileResponse类属于流式响应。其中StreamingHttpResponse类适用于大文本文件传输;FileResponse类适用于大二进制文件传输。

StreamingHttpResponse类将文件分段,每次传输一部分,分段大小可调;利用 python 的迭代器产生分段;可以是文件,也可以是任何大规模数据响应

文件下载实例代码:

fromdjango.http import StreamingHttpResponse

defbig_file_download(request):

deffile_iterator(file_name,chunk_size=512):

withopen(file_name) as  f:

while True:

c =f.read(chunk_size)

if c:

yield c

else:

break

   fname = "data.txt"

   response = StreamingHttpResponse(file_iterator(fname))

returnresponse

FileResponse是StreamingHttpResponse的子类;可以自动分段、自动迭代,适合二进制文件传输

文件下载实例:

import os
from django.http import StreamingHttpResponse,FileResponse
# Create your views here.
def homeproc2(request):
cwd = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
response = FileResponse(open(cwd+"/msgapp/templates/pyLOGO.png","rb"))
response['Content-Type']='application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="pyLOGO.png"'
return response

代码中Content-Type用于指定文件类型,Content-Disposition用于指定下载文件的默认名称。这两者是MIME类型的标准定义所定义的。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。

Pro HTML5 and CSS3 Design Patterns

Pro HTML5 and CSS3 Design Patterns

Michael Bowers / Apress / 2011-11-15 / GBP 35.50

Pro HTML5 and CSS3 Design Patterns is a reference book and a cookbook on how to style web pages using CSS3 and HTML5. It contains 350 ready--to--use patterns (CSS3 and HTML5 code snippets) that you ca......一起来看看 《Pro HTML5 and CSS3 Design Patterns》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具