camelCase
camelCase

Reputation: 532

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

Upvotes: 3

Views: 1607

Answers (1)

Paulo Bu
Paulo Bu

Reputation: 29794

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!

Upvotes: 8

Related Questions