在Python的Django架構中用流響應產生CSV檔案的教程

來源:互聯網
上載者:User

在Python的Django架構中用流響應產生CSV檔案的教程

   這篇文章主要介紹了在Python的Django架構中用流響應產生CSV檔案的教程,作者特別講到了防止CSV檔案中的中文避免出現亂碼等問題,需要的朋友可以參考下

  在Django裡,流式響應StreamingHttpResponse是個好東西,可以快速、節省記憶體地產生一個大型檔案。

  目前項目裡用於流式響應的一個是Eventsource,用於改善跨系統通訊時使用者產生的慢速的感覺。這個不細說了。

  還有一個就是產生一個大的csv檔案。

  當Django進程處於gunicorn或者uwsgi等web容器中時,如果響應超過一定時間沒有返回,就會被web容器終止掉,雖然我們可以通過加長web容器的逾時時間來繞過這個問題,但是畢竟還是治標不治本。要根本上解決這個問題,Python的產生器、Django架構提供的StreamingHttpResponse這個流式響應很有協助

  而在csv中,中文的處理也至關重要,要保證用excel開啟csv不亂碼什麼的。。為了節約空間,我就把所有代碼貼到一起了。。實際使用按照項目的規劃放置哈

  上代碼:

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

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)

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

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

        注< >:更多精彩教程請關注幫客之家編程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.