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

yipeiwu_com6年前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程序设计有所帮助。

相关文章

python使用magic模块进行文件类型识别方法

代码实例 python-magic是libmagic文件类型识别库的python接口。 libmagic通过根据预定义的文件类型列表检查它们的头文件来识别文件类型。 这个功能通过Unix...

python基础教程之基本内置数据类型介绍

Python基本内置数据类型有哪些 一些基本数据类型,比如:整型(数字)、字符串、元组、列表、字典和布尔类型。随着学习进度的加深,大家还会接触到更多更有趣的数据类型,python初学者入...

django连接mysql配置方法总结(推荐)

最近在学习django,学到第五章模型时,需要连接数据库,然后,在这里分享一下方法。 起初是不知道怎样配置mysql数据库,但是还好,django的官网上面有相关的配置方法,下面就直接...

python 弹窗提示警告框MessageBox的实例

需要安装pywin32模块,pip install pywin32 ##pip install pywin32 import win32api,win32con ##提醒OK...

numpy创建单位矩阵和对角矩阵的实例

在学习linear regression时经常处理的数据一般多是矩阵或者n维向量的数据形式,所以必须对矩阵有一定的认识基础。 numpy中创建单位矩阵借助identity()函数。更为准...