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

相关文章

TensorFlow的权值更新方法

一. MovingAverage权值滑动平均更新 1.1 示例代码: def create_target_q_network(self,state_dim,action_dim,ne...

全面理解Python中self的用法

刚开始学习Python的类写法的时候觉得很是麻烦,为什么定义时需要而调用时又不需要,为什么不能内部简化从而减少我们敲击键盘的次数?你看完这篇文章后就会明白所有的疑问。 self代表类的实...

Python学习入门之区块链详解

Python学习入门之区块链详解

前言 本文将给大家简单介绍关于区块链(BlockChain)的相关知识,并用Python做一简单实现。下面话不多说,来一起看看详细的介绍: 什么是区块链 简单来说,区块链就是把加密数据(...

python的pip安装以及使用教程

python的pip安装以及使用教程

pip的安装,以及使用pip安装包的方法,记录如下,分享给大家: —–安装python的时候勾选了下载pip,不知道为什么没下载。然后就偷懒想着需要哪个包再单独去下载就好了,然后!!!每...

深入浅析Python获取对象信息的函数type()、isinstance()、dir()

深入浅析Python获取对象信息的函数type()、isinstance()、dir()

type()函数: 使用type()函数可以判断对象的类型,如果一个变量指向了函数或类,也可以用type判断。 如: class Student(object): name = '...