加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

在Python,Django中,下载的文件总是空白的

发布时间:2020-12-20 11:27:30 所属栏目:Python 来源:网络整理
导读:我在Django中使用以下视图来创建一个文件并让浏览器下载它 def aux_pizarra(request): myfile = StringIO.StringIO() myfile.write("hello") response = HttpResponse(FileWrapper(myfile),content_type='text/plain') response['Content-Disposition'] = 'a
我在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

但下载的文件始终为空白.

有任何想法吗?
谢谢

解决方法

您必须将指针移动到缓冲区的开头并使用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']

在那里你可以看到如何将缓冲区指针指向开头以进行读取.

希望这可以帮助!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读