在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创建系统目录的方法
Mar 11 Python
分析Python的Django框架的运行方式及处理流程
Apr 08 Python
python解析基于xml格式的日志文件
Feb 25 Python
Python SqlAlchemy动态添加数据表字段实例解析
Feb 07 Python
Django框架使用富文本编辑器Uedit的方法分析
Jul 31 Python
python远程邮件控制电脑升级版
May 23 Python
在windows下使用python进行串口通讯的方法
Jul 02 Python
Django Channels 实现点对点实时聊天和消息推送功能
Jul 17 Python
使用Python内置模块与函数进行不同进制的数的转换
Apr 26 Python
解析Python 偏函数用法全方位实现
Jun 26 Python
python向xls写入数据(包括合并,边框,对齐,列宽)
Feb 02 Python
pandas提升计算效率的一些方法汇总
May 30 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模板类代码
2008/09/07 PHP
jQuery+php实现ajax文件即时上传的详解
2013/06/17 PHP
探讨:array2xml和xml2array以及xml与array的互相转化
2013/06/24 PHP
Thinkphp框架中D方法与M方法的区别
2016/12/23 PHP
php intval函数用法总结
2019/04/14 PHP
laravel 解决groupBy时出现的错误 isn't in Group By问题
2019/10/17 PHP
给artDialog 5.02 增加ajax get功能详细介绍
2012/11/13 Javascript
js multiple全选与取消全选实现代码
2012/12/04 Javascript
js获取UserControl内容为拼html时提供方便
2014/11/02 Javascript
JS实现从表格中动态删除指定行的方法
2015/03/31 Javascript
原生js实现移动开发轮播图、相册滑动特效
2015/04/17 Javascript
jQuery多条件筛选如何实现
2015/11/04 Javascript
js与jQuery实现checkbox复选框全选/全不选的方法
2016/01/05 Javascript
jQuery解决浏览器兼容性问题案例分析
2016/04/15 Javascript
如何在 Vue.js 中使用第三方js库
2017/04/25 Javascript
node.js到底要不要加分号浅析
2018/07/11 Javascript
Vue.js单向绑定和双向绑定实例分析
2018/08/14 Javascript
原生js实现公告滚动效果
2021/01/10 Javascript
bootstrap与pagehelper实现分页效果
2018/12/29 Javascript
如何用原生js写一个弹窗消息提醒插件
2019/05/24 Javascript
ES6 Map结构的应用实例分析
2019/06/26 Javascript
jquery.tagsinput.js实现记录checkbox勾选的顺序
2019/09/21 jQuery
uniapp微信小程序:key失效的解决方法
2021/01/20 Javascript
[42:32]完美世界DOTA2联赛PWL S2 LBZS vs FTD.C 第二场 11.27
2020/12/01 DOTA
Python实现的数据结构与算法之链表详解
2015/04/22 Python
详解python之协程gevent模块
2018/06/14 Python
使用django和vue进行数据交互的方法步骤
2019/11/11 Python
基于Python fminunc 的替代方法
2020/02/29 Python
详解使用python3.7配置开发钉钉群自定义机器人(2020年新版攻略)
2020/04/01 Python
Python读写锁实现实现代码解析
2020/11/28 Python
护理学毕业生求职信
2013/11/14 职场文书
遥感技术与仪器求职信
2014/02/22 职场文书
监察建议书范文
2014/03/12 职场文书
2014年社区民政工作总结
2014/12/02 职场文书
2015教师节师德演讲稿
2015/03/19 职场文书
javascript拖曳互换div的位置实现示例
2021/06/28 Javascript