zoukankan      html  css  js  c++  java
  • Django笔记:下载csv文件

    小csv文件
    如果是想要给用户返回一个较小的csv文件,那么使用普通的HttpResponse对象就可以了。
    示例:在访问对应的url时,浏览器就会自动下载对应的csv文件了。

    import csv
    
    
    def get_csv(request):
        # 创建一个HttpResponse响应对象,并指定content_type为text/csv
        response = HttpResponse(content_type='text/csv')
        # 将content内容作为csv附件形式发送回去,并指定文件名
        response['Content-Disposition'] = "attachment;filename='test.csv'"
        # 这是Python内置的csv库,可以将response对象当成一个文件句柄传入
        writer = csv.writer(response)
        writer.writerow(['username', 'age'])
        writer.writerow(['zhangsan', '20'])
        return response
    

    大csv文件
    如果是处理较大的csv文件的话就需要用到StreamingHttpResponse了,这个类是专门用来处理流数据的,使得后台在处理一些大型文件的时候,不会因为服务器处理时间过长而出现连接超时的问题。
    因为StreamingHttpResponse并不是继承自HttpResponse,而是直接继承自HttpResponseBase,所以与HttpResponse还是有一些区别需要注意下:

    • 没有content属性,而是streaming_content
    • streaming_content必须是一个可迭代的对象。
    • 没有write方法,也就是说不能将此对象当做文件一样往里面写入数据。
    • 此对象会启动一个进程来和客户端保持长连接,会很耗资源,所以如果不是特殊情况,尽量少用这个对象。
    from django.http import StreamingHttpResponse
    
    def large_csv_view(request):
        response = StreamingHttpResponse(content_type='text/csv')
        response['Content-Disposition'] = "attachment;filename='large.csv'"
        rows = ('Row {}, Row {}
    '.format(row, row) for row in range(1000000))
        response.streaming_content = rows
        return response
    
  • 相关阅读:
    POJ3094 UVALive3594 HDU2734 ZOJ2812 Quicksum【进制】
    UVALive5583 UVA562 Dividing coins
    POJ1979 HDU1312 Red and Black【DFS】
    POJ1979 HDU1312 Red and Black【DFS】
    POJ2386 Lake Counting【DFS】
    POJ2386 Lake Counting【DFS】
    HDU4394 Digital Square
    HDU4394 Digital Square
    UVA213 UVALive5152 Message Decoding
    UVA213 UVALive5152 Message Decoding
  • 原文地址:https://www.cnblogs.com/guyuyun/p/13832135.html
Copyright © 2011-2022 走看看