2017-01-17 3 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ファイルを送信することができますか?あなたが書き込まれているファイルのハンドルを渡して(とあなたのインデントのわからない、あなただけのwithブロックの外に可能性があり

答えて

3

ただ、読み取りモードでそれを再度開く。

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 
関連する問題