zoukankan      html  css  js  c++  java
  • 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类型的标准定义所定义的。

  • 相关阅读:
    第13组_16通信3班_045_OSPFv3作业
    RIPng配置(第十三组)
    基于IPV6的数据包分析(更新拓扑加入了linux主机和抓取133icmp包)(第十三组)
    vmware vsphere powercli 因为在此系统中禁止执行脚本
    vmware virtual machine must be running in order to be migrated
    flashback transaction闪回事务查询
    oracle 闪回功能详解
    linux下修改/dev/shm tmpfs文件系统大小
    vmware虚拟机guest系统重启后获得169.254.X.X的ip解决方法
    一键部署 PPTP server
  • 原文地址:https://www.cnblogs.com/xshan/p/8295789.html
Copyright © 2011-2022 走看看