小csv檔案
如果是想要給用戶回傳一個較小的csv檔案,那么使用普通的HttpResponse物件就可以了,
示例:在訪問對應的url時,瀏覽器就會自動下載對應的csv檔案了,
import csv
def get_csv(request):
# 創建一個HttpResponse回應物件,并指定content_type為text/csv
response = HttpResponse(content_type='text/csv')
# 將content內容作為csv附件形式發送回去,并指定檔案名
response['Content-Disposition'] = "attachment;filename='test.csv'"
# 這是Python內置的csv庫,可以將response物件當成一個檔案句柄傳入
writer = csv.writer(response)
writer.writerow(['username', 'age'])
writer.writerow(['zhangsan', '20'])
return response
大csv檔案
如果是處理較大的csv檔案的話就需要用到StreamingHttpResponse了,這個類是專門用來處理流資料的,使得后臺在處理一些大型檔案的時候,不會因為服務器處理時間過長而出現連接超時的問題,
因為StreamingHttpResponse并不是繼承自HttpResponse,而是直接繼承自HttpResponseBase,所以與HttpResponse還是有一些區別需要注意下:
- 沒有
content屬性,而是streaming_content, streaming_content必須是一個可迭代的物件,- 沒有
write方法,也就是說不能將此物件當做檔案一樣往里面寫入資料, - 此物件會啟動一個行程來和客戶端保持長連接,會很耗資源,所以如果不是特殊情況,盡量少用這個物件,
from django.http import StreamingHttpResponse
def large_csv_view(request):
response = StreamingHttpResponse(content_type='text/csv')
response['Content-Disposition'] = "attachment;filename='large.csv'"
rows = ('Row {}, Row {}\n'.format(row, row) for row in range(1000000))
response.streaming_content = rows
return response
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/176524.html
標籤:Python
上一篇:Django筆記:視圖
下一篇:Django筆記:視圖
