File downloaded always blank in Python, Django

感情迁移 提交于 2019-12-10 18:18:06

问题


I am using the following view in Django to create a file and make the browser download it

    def aux_pizarra(request):

        myfile = StringIO.StringIO()
        myfile.write("hello")       
        response = HttpResponse(FileWrapper(myfile), content_type='text/plain')
        response['Content-Disposition'] = 'attachment; filename=prueba.txt'
        return response

But the file downloaded is always blank.

Any ideas? Thanks


回答1:


You have to move the pointer to the beginning of the buffer with seek and use flush just in case the writing hasn't performed.

from django.core.servers.basehttp import FileWrapper
import StringIO

def aux_pizarra(request):

    myfile = StringIO.StringIO()
    myfile.write("hello")       
    myfile.flush()
    myfile.seek(0) # move the pointer to the beginning of the buffer
    response = HttpResponse(FileWrapper(myfile), content_type='text/plain')
    response['Content-Disposition'] = 'attachment; filename=prueba.txt'
    return response

This is what happens when you do it in a console:

>>> import StringIO
>>> s = StringIO.StringIO()
>>> s.write('hello')
>>> s.readlines()
[]
>>> s.seek(0)
>>> s.readlines()
['hello']

There you can see how seek is necessary to bring the buffer pointer to the beginning for reading purposes.

Hope this helps!



来源:https://stackoverflow.com/questions/16703511/file-downloaded-always-blank-in-python-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!