Python,Django中的文件总是空白 [英] File downloaded always blank in Python, Django

查看:146
本文介绍了Python,Django中的文件总是空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django中使用以下视图来创建一个文件并使浏览器下载

  def aux_pizarra(request) :

myfile = StringIO.StringIO()
myfile.write(hello)
response = HttpResponse(FileWrapper(myfile),content_type ='text / plain')
response ['Content-Disposition'] ='attachment;文件名= prueba.txt'
返回响应

但下载的文件始终为空。 / p>

任何想法?
谢谢

解决方案

你必须将指针移动到缓冲区的开头,使用 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)#将指针移动到缓冲区的开头
response = HttpResponse (FileWrapper(myfile),content_type ='text / plain')
response ['Content-Disposition'] ='attachment;文件名= prueba.txt'
返回响应

这样做会发生什么控制台:

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

你可以看到如何 seek 需要将缓冲区指针带到开头进行阅读。



希望这有帮助!


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

解决方案

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!

这篇关于Python,Django中的文件总是空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆