Python Django httpresponse汽提CR

Python Django httpresponse汽提CR,python,django,httpresponse,Python,Django,Httpresponse,当我打开使用以下代码生成的文本文件附件时,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(fil

当我打开使用以下代码生成的文本文件附件时,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
the_file=tempfile.TemporaryFile(mode='w+b')
_文件.seek(0)
filestring=_file.read()文件
response=HttpResponse(文件字符串,
mimetype=“text/plain”)
response['Content-Length']=_文件.tell()
响应['Content-Disposition']='附件;filename=“4cos_example.txt”
返回响应
如果使用此方法,我会在文件中获得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
the_file=open('myfile.txt','w+'))
_file.close文件
_file=open('myfile.txt','rb')
filestring=_file.read()文件
response=HttpResponse(文件字符串,
mimetype=“text/plain”)
response['Content-Length']=_文件.tell()
响应['Content-Disposition']='附件;filename=“4cos_example.txt”
返回响应

我觉得解决办法应该是显而易见的。但是我不能关闭临时文件并以二进制模式重新打开它(保留CR/LR)。见鬼,我甚至不确定我在如何正确地做到这一点:)尽管如此,我还是希望在配置完成后将此数据作为附件传递给用户,并使其在记事本中正确显示。tempfile是错误的解决方案,还是tempfile的一个机制可以帮我解决这个问题,而不必使用磁盘上的文件IO。

使用
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

仅供参考,如果这是一个非常大的响应,您也可以使用。但只有在需要时才这样做,因为像
Content Length
这样的标题将无法自动添加。

为什么要使用临时文件?你给它写信,然后通读整件事。看起来你得到的不多。真的,这更多的是作为构建配置文件的脚本启动我的项目。当我对脚本进行webified时,我不再需要将文件写入磁盘,而是通过httpresponse作为文本附件提供配置。我当然想一起把这个文件处理掉,但向后看,我试图找出为什么我失去了CR/LF而留下了LF。无论如何,CR/LF问题仍然存在问题,除非我以二进制方式打开文件并以这种方式提供它。神奇的是当我关闭文件,然后以“rb”重新打开它时。有没有一种方法可以用字符串而不是文件来复制这种行为?这非常有效。接收端没有我需要的中间文件和CR/LF。非常感谢你。我没有考虑过response.write:)