【问题标题】:File downloaded always blank in Python, Django在Python,Django中下载的文件总是空白
【发布时间】:2013-05-18 04:45:14
【问题描述】:

我在 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

但是下载的文件总是空白的。

有什么想法吗? 谢谢

【问题讨论】:

    标签: python django web-applications django-views


    【解决方案1】:

    您必须使用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 是如何将缓冲区指针带到开头以供读取的。

    希望这会有所帮助!

    【讨论】:

    • 下载的文件还是空白:S
    • 我将更新问题,说明它在解释器中的工作方式。
    • 我不知道为什么它以前不起作用。但我又试了一次,你的解决方案有效!非常感谢您的帮助。
    • 大声笑,我很高兴 :) 可能是浏览器缓存问题或其他问题!不客气:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 2011-03-09
    • 1970-01-01
    • 2019-06-11
    • 1970-01-01
    相关资源
    最近更新 更多