本文實例講述了python django下載大的csv文件實現(xiàn)方法。分享給大家供大家參考,具體如下:
接手他人項目,第一個要優(yōu)化的點是導出csv的功能,而且要支持比較多的數(shù)據(jù)導出,以前用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
另外有需要云服務器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。