在Python的Django框架中用流響應(yīng)生成CSV文件的教程
在Django里,流式響應(yīng)StreamingHttpResponse是個好東西,可以快速、節(jié)省內(nèi)存地產(chǎn)生一個大型文件。
目前項目里用于流式響應(yīng)的一個是Eventsource,用于改善跨系統(tǒng)通訊時用戶產(chǎn)生的慢速的感覺。這個不細(xì)說了。
還有一個就是生成一個大的csv文件。
當(dāng)Django進(jìn)程處于gunicorn或者uwsgi等web容器中時,如果響應(yīng)超過一定時間沒有返回,就會被web容器終止掉,雖然我們可以通過加長web容器的超時時間來繞過這個問題,但是畢竟還是治標(biāo)不治本。要根本上解決這個問題,Python的生成器、Django框架提供的StreamingHttpResponse這個流式響應(yīng)很有幫助
而在csv中,中文的處理也至關(guān)重要,要保證用excel打開csv不亂碼什么的。。為了節(jié)約空間,我就把所有代碼貼到一起了。。實際使用按照項目的規(guī)劃放置哈
上代碼:
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 = [['第一行','數(shù)據(jù)1'],
['第二行','數(shù)據(jù)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
- Django的HttpRequest和HttpResponse對象詳解
- Django使用HttpResponse返回圖片并顯示的方法
- Django使用httpresponse返回用戶頭像實例代碼
- django rest framework之請求與響應(yīng)(詳解)
- django從請求到響應(yīng)的過程深入講解
- 從請求到響應(yīng)過程中django都做了哪些處理
- Django框架的使用教程路由請求響應(yīng)的方法
- Django 中使用流響應(yīng)處理視頻的方法
- 詳解從Django Rest Framework響應(yīng)中刪除空字段
- Django 響應(yīng)數(shù)據(jù)response的返回源碼詳解
- django創(chuàng)建簡單的頁面響應(yīng)實例教程
- Django框架HttpResponse對象用法實例分析
相關(guān)文章
python輸出100以內(nèi)的質(zhì)數(shù)與合數(shù)實例代碼
本文通過實例代碼給大家介紹了python輸出100以內(nèi)的質(zhì)數(shù)與合數(shù)的方法,非常不錯,具有一定的參考借鑒價值,需要的朋友參考下吧2018-07-07
Python實踐之使用Pandas進(jìn)行數(shù)據(jù)分析
在數(shù)據(jù)分析領(lǐng)域,Python的Pandas庫是一個非常強(qiáng)大的工具。這篇文章將為大家詳細(xì)介紹如何使用Pandas進(jìn)行數(shù)據(jù)分析,希望對大家有所幫助2023-04-04
Windows下安裝python MySQLdb遇到的問題及解決方法
這篇文章主要介紹了Windows下安裝python MySQLdb遇到的問題及解決方法,需要的朋友可以參考下2017-03-03
詳解Django+Uwsgi+Nginx的生產(chǎn)環(huán)境部署
這篇文章主要介紹了Django + Uwsgi + Nginx 的生產(chǎn)環(huán)境部署,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-06-06

