【问题标题】:Django httpresponse stripping CRDjango httpresponse 剥离 CR
【发布时间】:2013-11-03 00:33:10
【问题描述】:

当我打开使用以下代码生成的文本文件附件时,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。

【问题讨论】:

  • 你为什么使用 TemporaryFile?你给它写信,然后阅读整个内容。看起来你得到的不多。
  • 真的,它更像是一个将我的项目作为构建配置文件的脚本启动的工件。当我将脚本网络化时,我不再需要将文件写入磁盘,而是通过 httpresponse 将配置作为文本附件提供。我当然想一起摆脱文件,但向后工作,我试图确定为什么我失去了 CR/LF 并留下了 LF。无论如何,除非我将文件作为二进制文件打开并以这种方式提供,否则 CR/LF 问题仍然存在。
  • 魔术似乎是当我关闭文件,然后以'rb'重新打开它。有没有办法用字符串而不是文件来复制这种行为?

标签: python django httpresponse


【解决方案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

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

【讨论】:

  • 这非常有效。接收端没有我需要的中间文件和 CR/LF。太感谢了。 response.write 不是我考虑过的:)
猜你喜欢
  • 1970-01-01
  • 2023-03-10
  • 2010-10-17
  • 2011-08-21
  • 2017-03-03
  • 2020-12-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多