3

Djangoで次のビューを使用してファイルを作成し、ブラウザにダウンロードさせています

    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

しかし、ダウンロードされたファイルは常に空白です。

何か案は?ありがとう

4

1 に答える 1

8

ポインターをバッファーの先頭に移動し、書き込みが実行されなかった場合に備えseekて使用する必要があります。flush

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

これをコンソールで実行すると、次のようになります。

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

seek読み取り目的でバッファ ポインタを先頭に移動する必要があることがわかります。

お役に立てれば!

于 2013-05-23T00:20:25.090 に答える