属性错误:“ str”对象没有属性“ read” python-django

时间:2019-01-25 02:28:34

标签: python django django-rest-framework zipfile file-system-storage

因此,这里的情况是,我有一个端点,该端点将提取一个zip文件,将其解压缩并暂时保存到媒体目录中。这是整个代码

def get_filenames(path_for_zip):
    with ZipFile(path_for_zip, 'r') as zip:
        return zip.namelist()


class Upload(View):
    def post(self, request):

        context = {}

        upload_file = request.FILES['document']
        unzip_file = get_filenames(upload_file)
        for files in unzip_file:
            print(files)
            fs = FileSystemStorage()
            fs.save('read.jpg', files)




        return render (request, 'toDo_app.html', context)

如您所见,我正在使用FileSystemStorageZipFile正确解压缩,我可以在print(files)中看到它,但问题出在FileSystemStorage上,我想它没有保存下来,出现了这个错误:

attribute error 'str' object has no attribute 'read'. 

请指出我做错了什么以及应该如何解决。谢谢。

1 个答案:

答案 0 :(得分:1)

@zeed名称列表返回列表中文件的名称,即zip中的字符串。上载时,读取/打开文件以进行缓冲和上载

for files in unzip_file:
    print(files)
    fs = FileSystemStorage()
    with open(files, "rb") as outstream:
        fs.save('read.jpg', outstream)