Django的视图流式响应机制

Django的视图流式响应机制

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

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

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

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

文件下载实例代码:

from django.http import StreamingHttpResponse

def big_file_download(request):

    def file_iterator(file_name,chunk_size=512):

        with open(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))

    return response

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类型的标准定义所定义的。

原文地址:https://www.cnblogs.com/xshan/p/8295789.html