在Python的Django框架中用流响应生成CSV文件的教程


Posted in Python onMay 02, 2015

在Django里,流式响应StreamingHttpResponse是个好东西,可以快速、节省内存地产生一个大型文件。

目前项目里用于流式响应的一个是Eventsource,用于改善跨系统通讯时用户产生的慢速的感觉。这个不细说了。

还有一个就是生成一个大的csv文件。

当Django进程处于gunicorn或者uwsgi等web容器中时,如果响应超过一定时间没有返回,就会被web容器终止掉,虽然我们可以通过加长web容器的超时时间来绕过这个问题,但是毕竟还是治标不治本。要根本上解决这个问题,Python的生成器、Django框架提供的StreamingHttpResponse这个流式响应很有帮助

而在csv中,中文的处理也至关重要,要保证用excel打开csv不乱码什么的。。为了节约空间,我就把所有代码贴到一起了。。实际使用按照项目的规划放置哈

上代码:

from __future__ import absolute_import
import csv
import codecs
import cStringIO


class Echo(object):

  def write(self, value):
    return value

class UnicodeWriter:

  """
  A CSV writer which will write rows to CSV file "f",
  which is encoded in the given encoding.
  """

  def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
    # Redirect output to a queue
    self.queue = cStringIO.StringIO()
    self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
    self.stream = f
    self.encoder = codecs.getincrementalencoder(encoding)()

  def writerow(self, row):
    self.writer.writerow([handle_column(s) for s in row])
    # Fetch UTF-8 output from the queue ...
    data = self.queue.getvalue()
    data = data.decode("utf-8")
    # ... and reencode it into the target encoding
    data = self.encoder.encode(data)
    # write to the target stream
    value = self.stream.write(data)
    # empty queue
    self.queue.truncate(0)
    return value

  def writerows(self, rows):
    for row in rows:
      self.writerow(row)
from django.views.generic import View
from django.http.response import StreamingHttpResponse

class ExampleView(View):
  headers=['一些','表头']
  def get(self,request):
    result = [['第一行','数据1'],
         ['第二行','数据2']]
    echoer = Echo()
    writer = UnicodeWriter(echoer)
    def csv_itertor():
        yield codecs.BOM_UTF8
        yield writer.writerow(self.headers)
        for column in result:
          yield writer.writerow(column)

    response = StreamingHttpResponse(
      (row for row in csv_itertor()),
      content_type="text/csv;charset=utf-8")
    response['Content-Disposition'
         ] = 'attachment;filename="example.csv"'
    return response

Python 相关文章推荐
用Python实现通过哈希算法检测图片重复的教程
Apr 02 Python
Python中用PIL库批量给图片加上序号的教程
May 06 Python
Eclipse中Python开发环境搭建简单教程
Mar 23 Python
对python中执行DOS命令的3种方法总结
May 12 Python
pandas分别写入excel的不同sheet方法
Dec 11 Python
基于OpenCV python3实现证件照换背景的方法
Mar 22 Python
python3.6+django2.0+mysql搭建网站过程详解
Jul 24 Python
python列表推导式入门学习解析
Dec 02 Python
Python数据可视化:顶级绘图库plotly详解
Dec 07 Python
tensorflow实现对张量数据的切片操作方式
Jan 19 Python
关于Keras模型可视化教程及关键问题的解决
Jan 24 Python
python爬虫看看虎牙女主播中谁最“顶”步骤详解
Dec 01 Python
详细解读Python中的__init__()方法
May 02 #Python
举例讲解Python的Tornado框架实现数据可视化的教程
May 02 #Python
Python的Bottle框架中返回静态文件和JSON对象的方法
Apr 30 #Python
使用Python编写提取日志中的中文的脚本的方法
Apr 30 #Python
简单的连接MySQL与Python的Bottle框架的方法
Apr 30 #Python
Python的Bottle框架中实现最基本的get和post的方法的教程
Apr 30 #Python
Python中使用Beautiful Soup库的超详细教程
Apr 30 #Python
You might like
PHP 文件类型判断代码
2009/03/13 PHP
php 生成随机验证码图片代码
2010/02/08 PHP
PHP学习笔记之字符串编码的转换和判断
2014/05/22 PHP
详解php伪造Referer请求反盗链资源
2019/01/24 PHP
Yii框架核心组件类实例详解
2019/08/06 PHP
jQuery 全选效果实现代码
2009/03/23 Javascript
关于javascript document.createDocumentFragment()
2009/04/04 Javascript
左右悬浮可分组的网站QQ在线客服代码(可谓经典)
2012/12/21 Javascript
js获取dom的高度和宽度(可见区域及部分等等)
2013/06/13 Javascript
jquery pagination分页插件使用详解(后台struts2)
2017/01/22 Javascript
纯JS实现图片验证码功能并兼容IE6-8(推荐)
2017/04/19 Javascript
页面间固定参数,通过cookie传值的实现方法
2017/05/31 Javascript
ionic选择多张图片上传的示例代码
2017/10/10 Javascript
使用 Javascript 实现浏览器推送提醒功能的示例
2017/11/03 Javascript
Vue自定义指令上报Google Analytics事件统计的方法
2019/02/25 Javascript
浅谈关于vue中scss公用的解决方案
2019/12/02 Javascript
用实例详解Python中的Django框架中prefetch_related()函数对数据库查询的优化
2015/04/01 Python
实例Python处理XML文件的方法
2015/08/31 Python
Python实现简单字典树的方法
2016/04/29 Python
解决Ubuntu pip 安装 mysql-python包出错的问题
2018/06/11 Python
python+splinter实现12306网站刷票并自动购票流程
2018/09/25 Python
完美解决Python matplotlib绘图时汉字显示不正常的问题
2019/01/29 Python
很酷的python表白工具 你喜欢我吗
2019/04/11 Python
Python 循环终止语句的三种方法小结
2019/06/24 Python
python 牛顿法实现逻辑回归(Logistic Regression)
2020/10/15 Python
使用CSS3实现圆角,阴影,透明
2014/12/23 HTML / CSS
北欧最好的童装网上商店:Babyshop
2019/09/15 全球购物
Ariat官网:美国马靴和服装品牌
2019/12/16 全球购物
意大利时尚精品店:Nugnes 1920
2020/02/10 全球购物
群众路线剖析材料
2014/09/30 职场文书
党的群众路线教育实践活动查摆问题及整改措施
2014/10/10 职场文书
2014年采购员工作总结
2014/11/18 职场文书
幼儿园教师师德表现自我评价
2015/03/05 职场文书
员工拾金不昧表扬稿
2015/05/05 职场文书
超级详细实用的pycharm常用快捷键
2021/05/12 Python
Windows和Linux上部署Golang并运行程序
2022/04/22 Servers