python django下載大的csv文件實現(xiàn)方法分析
本文實例講述了python django下載大的csv文件實現(xiàn)方法。分享給大家供大家參考,具體如下:
接手他人項目,第一個要優(yōu)化的點是導(dǎo)出csv的功能,而且要支持比較多的數(shù)據(jù)導(dǎo)出,以前用php實現(xiàn)過,直接寫入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() # 寫B(tài)OM 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
假設(shè)遍歷結(jié)果集的代碼如下:
headers = ["col1", "col2", ..., "coln"] def genRows(): for obj in objList: yield [obj.col1, obj.col2, ...obj.coln] #這樣調(diào)用,返回response return outputCSV(genRows(), "file.csv", headers)
有人可能會問,為什么不用python自帶的csv.writer?因為生成的csv兼容不太好啊,關(guān)于csv的兼容性,可以看前面這篇避免UTF-8的csv文件打開中文出現(xiàn)亂碼的方法。
參考:http://stackoverflow.com/questions/5146539/streaming-a-csv-file-in-django
希望本文所述對大家基于Django框架的Python程序設(shè)計有所幫助。
相關(guān)文章
Python NumPy實現(xiàn)數(shù)組排序與過濾示例分析講解
NumPy是Python的一種開源的數(shù)值計算擴展,它支持大量的維度數(shù)組與矩陣運算,這篇文章主要介紹了使用NumPy實現(xiàn)數(shù)組排序與過濾的方法,需要的朋友們下面隨著小編來一起學(xué)習吧2023-05-05python實現(xiàn)將多個文件分配到多個文件夾的方法
今天小編就為大家分享一篇python實現(xiàn)將多個文件分配到多個文件夾的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01