2017-01-17 73 views
3

我有這樣的代碼:的Django的視圖生成CSV文件,並下載

with open('stockitems_misuper.csv', 'wb') as myfile: 
     wr = csv.writer(myfile, quoting=csv.QUOTE_ALL) 
     wr.writerows(file_rows) 

    response = HttpResponse(myfile, content_type='text/csv') 
    response['Content-Disposition'] = 'attachment; filename=stockitems_misuper.csv' 
    return response 

我得到的錯誤:

I/O operation on closed file

我怎樣才能創建的CSV文件發送到前端?

回答

3

要傳遞的文件句柄寫入(而不是確保您的壓痕,你可能只是在with外塊。

只需打開它在讀模式。

with open('stockitems_misuper.csv', 'wb') as myfile: 
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL) 
    wr.writerows(file_rows) 

with open('stockitems_misuper.csv', 'rb') as myfile: 
    response = HttpResponse(myfile, content_type='text/csv') 
    response['Content-Disposition'] = 'attachment; filename=stockitems_misuper.csv' 
    return response 

或更好:寫入io.StringIO()實例,並通過該實例,避免創建該文件。

import io 

buffer = io.StringIO() 
wr = csv.writer(buffer, quoting=csv.QUOTE_ALL) 
wr.writerows(file_rows) 

buffer.seek(0) 
response = HttpResponse(buffer, content_type='text/csv') 
response['Content-Disposition'] = 'attachment; filename=stockitems_misuper.csv' 

return response