当我打开使用以下代码生成的文本文件附件时,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 是这里的错误解决方案,还是有一种 tempfile 机制可以为我解决这个问题,而无需在磁盘上使用文件 IO。