2013-11-01 2 views
2

아래 코드를 사용하여 생성 된 텍스트 파일 첨부 파일을 열면 HTTP 응답이 항상 각 행의 CR을 제거하는 것처럼 보입니다.이 파일의 사용자는 메모장을 사용하므로 CR/각 라인에 LF. 나는이 방법을 사용하는 경우Django httpresponse stripping CR

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를 사용하지 않고도이 문제를 해결할 임시 파일 메커니즘이 있습니다. 대신 TemporaryFile를 사용

+0

왜 TemporaryFile을 사용하고 있습니까? 당신은 그것에 글을 쓰고 모든 것을 읽습니다. 당신이 많이 얻는 것처럼 보이지 않습니다. –

+0

정말, 구성 파일을 작성한 스크립트로 내 프로젝트를 시작하는 아티팩트가 많습니다. 스크립트를 웹화 할 때 디스크에 파일을 더 이상 쓸 필요가 없으며 대신 httpresponse를 통해 텍스트 첨부 파일로 설정을 제공했습니다. 나는 분명히 함께 파일을 없애고 싶지만, 거꾸로 일하면서 왜 내가 CR/LF를 잃어 버리고 LF로 떠났는지를 밝혀 내려고했다. 그럼에도 불구하고 CR/LF 문제는 여전히 파일을 바이너리로 열지 않으면 문제가됩니다. – downbySF

+0

Magic은 파일을 닫은 후 'rb'로 다시 여는 것 같습니다. 이 동작을 파일 대신 문자열로 복제하는 방법이 있습니까? – downbySF

답변

1

, 단지 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과 같은 헤더를 자동으로 추가 할 수 없기 때문에 그렇게하십시오.

+0

이것은 완벽하게 작동했습니다. 수신인 측에 중개 파일 및 CR/LF가 필요하지 않습니다. 정말 고맙습니다. response.write 내가 생각했던 뭔가가 아니었다 :) – downbySF

관련 문제