2

以下のコードを使用して生成されたテキスト ファイルの添付ファイルを開くと、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の仕組みがありますか。

4

1 に答える 1

1

を使用する代わりに、次を使用TemporaryFileしますHttpResponse

response = HttpResponse('', content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename="4cos_example.txt"'
response.write('first line\r\n')
response.write('second line\r\n')    
return response

参考までに、これが非常に大きな応答である場合は、 も使用できますStreamingHttpResponseContent-Lengthただし、ヘッダーのようなものは自動的に追加できないため、必要な場合にのみ行ってください。

于 2013-11-02T16:33:10.230 に答える