python django下载大的csv文件实现方法分析

yipeiwu_com5年前Python基础

本文实例讲述了python django下载大的csv文件实现方法。分享给大家供大家参考,具体如下:

接手他人项目,第一个要优化的点是导出csv的功能,而且要支持比较多的数据导出,以前用php实现过,直接写入php://output就行了,django怎么做呢?如下:

借助django的StreamingHttpResponse和python的generator

def outputCSV(rows, fname="output.csv", headers=None):
  def getContent(fileObj):
    fileObj.seek(0)
    data = fileObj.read()
    fileObj.seek(0)
    fileObj.truncate()
    return data
  def genCSV(rows, headers):
    # 准备输出
    output = cStringIO.StringIO()
    # 写BOM
    output.write(bytearray([0xFF, 0xFE]))
    if headers != None and isinstance(headers, list):
      headers = codecs.encode("\t".join(headers) + "\n", "utf-16le")
      output.write(headers)
      yield getContent(output)
    for row in rows:
      rowData = codecs.encode("\t".join(row) + "\n", "utf-16le")
      output.write(rowData)
      yield getContent(output) #因为StreamingHttpResponse需要一个Iterator
    output.close()
  resp = StreamingHttpResponse(genCSV(rows, headers))
  resp["Content-Type"] = "application/vnd.ms-excel; charset=utf-16le"
  resp["Content-Type"] = "application/octet-stream"
  resp["Content-Disposition"] = "attachment;filename=" + fname
  resp["Content-Transfer-Encoding"] = "binary"
  return resp

假设遍历结果集的代码如下:

headers = ["col1", "col2", ..., "coln"]
def genRows():
      for obj in objList:
        yield [obj.col1, obj.col2, ...obj.coln]   
#这样调用,返回response
return outputCSV(genRows(), "file.csv", headers)

有人可能会问,为什么不用python自带的csv.writer?因为生成的csv兼容不太好啊,关于csv的兼容性,可以看前面这篇避免UTF-8的csv文件打开中文出现乱码的方法

参考:http://stackoverflow.com/questions/5146539/streaming-a-csv-file-in-django

希望本文所述对大家基于Django框架的Python程序设计有所帮助。

相关文章

CentOS7下python3.7.0安装教程

记录了CentOS7 安装python3.7.0的详细过程,供大家参考,具体内容如下 1.下载及解压 python3.7的安装包可从官网下载上传到主机,也可以用wget直接下载。 [...

python select.select模块通信全过程解析

python select.select模块通信全过程解析

要理解select.select模块其实主要就是要理解它的参数, 以及其三个返回值。 select()方法接收并监控3个通信列表, 第一个是所有的输入的data,就是指外部发过来的数据...

在python里面运用多继承方法详解

在python里面运用多继承方法详解

如何在PYTHON里面运用多继承 class Father: def hobby(self): print("love to play video game.")...

详谈Python中列表list,元祖tuple和numpy中的array区别

1.列表 list是处理一组有序项目的数据结构,即你可以在一个列表中存储一个序列的项目。列表中的项目。列表中的项目应该包括在方括号中,这样python就知道你是在指明一个列表。一旦你创建...

浅谈python为什么不需要三目运算符和switch

对于三目运算符(ternary operator),python可以用conditional expressions来替代 如对于x<5?1:0可以用下面的方式来实现...