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使用sort和class实现的多级排序功能示例

本文实例讲述了Python使用sort和class实现的多级排序功能。分享给大家供大家参考,具体如下: # -*- coding:utf-8 -*- import random cl...

python实现flappy bird小游戏

本文实例为大家分享了python实现flappy bird游戏的具体代码,供大家参考,具体内容如下 flappygamemain.py # -*- coding: utf-8 -*-...

Python 3中的yield from语法详解

前言 最近在捣鼓Autobahn,它有给出个例子是基于asyncio 的,想着说放到pypy3上跑跑看竟然就……失败了。 pip install asyncio直接报invalid sy...

Python通过select实现异步IO的方法

本文实例讲述了Python通过select实现异步IO的方法。分享给大家供大家参考。具体如下: 在Python中使用select与poll比起在C中使用简单得多。select函数的参数是...

Python读取xlsx文件的实现方法

脚本如下: from openpyxl import load_workbook workbook = load_workbook(u'/tmp/test.xlsx') #找到需...