【发布时间】: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