内容简介: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类型的标准定义所定义的。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- 从JavaScript属性描述器剖析Vue.js响应式视图
- iOS小技巧·把子视图控制器的视图添加到父视图控制器
- CouchDB 视图简介及增量更新视图的方法
- c# – 将数据从部分视图传递到其父视图
- Django 基于函数的视图与基于类的视图
- 类视图
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Data Structures and Algorithms in Java
Robert Lafore / Sams / 2002-11-06 / USD 64.99
Data Structures and Algorithms in Java, Second Edition is designed to be easy to read and understand although the topic itself is complicated. Algorithms are the procedures that software programs use......一起来看看 《Data Structures and Algorithms in Java》 这本书的介绍吧!