以下のコードを使用して生成されたテキスト ファイルの添付ファイルを開くと、HTTP 応答は常に各行から CR を削除しているように見えます。このファイルのユーザーはメモ帳を使用するため、各行に CR/LF が必要です。
the_file = tempfile.TemporaryFile(mode='w+b')
<procedure call to generate lines of text in "the_file">
the_file.seek(0)
filestring = the_file.read()
response = HttpResponse(filestring,
mimetype="text/plain")
response['Content-Length'] = the_file.tell()
response['Content-Disposition'] = 'attachment; filename="4cos_example.txt"'
return response
この方法を使用すると、ファイルに CR/LF が含まれますが、ファイルをディスクに書き込む必要はまったくないので、良い解決策ではないようです。
the_file = open('myfile.txt','w+')
<procedure call to generate lines of text in "the_file">
the_file.close
the_file = open('myfile.txt','rb')
filestring = the_file.read()
response = HttpResponse(filestring,
mimetype="text/plain")
response['Content-Length'] = the_file.tell()
response['Content-Disposition'] = 'attachment; filename="4cos_example.txt"'
return response
解決策は明白であるべきだと思います。しかし、一時ファイルを閉じて、バイナリ モードで再度開くことはできません (CR/LR を保持します)。これを正しく行う方法に関して、私が正しい球場にいるかどうかさえわかりません:)それでもなお、構成が組み立てられた後、このデータを添付ファイルとしてユーザーに渡し、正しく表示させたいと思いますメモ帳で。ここでtempfileは間違った解決策ですか、それともディスク上のファイルIOを使用せずにこの問題を解決するtempfileの仕組みがありますか。