Skip to content Skip to sidebar Skip to footer

File Downloaded Always Blank In Python, Django

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('

Solution 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

defaux_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!

Post a Comment for "File Downloaded Always Blank In Python, Django"