文件没有缓冲区接口 [英] file does not have buffer interface

查看:141
本文介绍了文件没有缓冲区接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的views.py中有一个函数。这就像这样

  from django.core.files.uploadedfile import SimpleUploadedFile 
def get_file(self,url):
#pdb.set_trace()
result = urllib.urlretrieve(url)
fi = open(result [0])
fi_name = os.path.basename(url)
suf = SimpleUploadedFile(fi_name,fi)
return suf

同时创建SimpleUploadedFile对象我收到错误说

  TypeError:file没有缓冲区界面

我尝试将开放模式更改为'rb'。但仍然得到同样的错误
Plz帮助我出来

解决方案

SimpleUploadedFile 需要实际的文件内容,而不是文件对象。所以你可以修复这样的代码:

  suf = SimpleUploadedFile(fi_name,fi.read())

我必须说,虽然我不知道你为什么使用urlretrieve,它将内容保存到本地的临时文件,那么必须打开阅读。更好地使用 urlopen 并直接传递:

  result = urllib。 urlopen(url)
fi_name = os.path.basename(url)
suf = SimpleUploadedFile(fi_name,result.read())


i have a function in my views.py. It is like this

from django.core.files.uploadedfile import SimpleUploadedFile
def get_file(self, url):
    # pdb.set_trace()
    result = urllib.urlretrieve(url)
    fi = open(result[0])
    fi_name = os.path.basename(url)
    suf = SimpleUploadedFile(fi_name, fi)
    return suf

while creating SimpleUploadedFile object i get the error saying

TypeError: file doesnot have buffer interface

I tried changing open mode to 'rb'. But still get the same error Plz help me out

解决方案

SimpleUploadedFile needs the actual file content, rather than a file object. So you could fix your code like this:

suf = SimpleUploadedFile(fi_name, fi.read())

I must say though I don't know why you are using urlretrieve, which saves the content to a local temp file which you then must open and read. Better to use urlopen and pass it directly:

result = urllib.urlopen(url)
fi_name = os.path.basename(url)
suf = SimpleUploadedFile(fi_name, result.read())

这篇关于文件没有缓冲区接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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