Django解压缩文件,将内容添加到数据库

时间:2011-08-09 13:43:52

标签: python database django os.walk

我正在尝试创建一个让管理员上传zip文件的系统,然后脚本会自动使用signals解压缩,搜索 {{1}中的所有文件}。创建jpg,png个并根据它生成数据库记录。

在模型中,我有listProject表格,PhotoPhotoMany-to-One又名Foreign Key的关系。

下面的脚本是我正在工作的信号。我可以毫无错误地获得Project,并且在手动运行时脚本运行良好。

长时间调试,我认为instance.file_zip.path有问题,但我不知道如何修复它,因为我实际上并不理解它为什么会出错。 提取部分工作正常,我只是把它们放在这里作为参考,很可能你不需要阅读和理解它。

belongs_to=instance

更新

@receiver(post_save, sender=Project)
def unzip_and_process(sender, instance, **kwargs):
    #project_zip = FieldFile.open(file_zip, mode='rb')
    file_path = instance.file_zip.path
    file_list = []
    with zipfile.ZipFile(file_path, 'r') as project_zip:
        project_zip.extractall(re.search('[^\s]+(?=\.zip)', file_path).group(0))
        project_zip.close()
    for root, dirs, files in os.walk(file_path):
        for filename in files:
            file_list.append(os.path.join(root, filename))
    photo_list = filter(filter_photos, file_list)
    for photo in photo_list:
        print 'Processing %s'%photo
        p = Photo.objects.create(belongs_to=instance, img=photo, desc='Processed from zipfile')
        p.save()

2 个答案:

答案 0 :(得分:2)

django-photologue有一些你想要的东西,他们创建了一个类似的hack上传zipfile。

链接:http://code.google.com/p/django-photologue/如果您不想谷歌

甚至,zip上传类是GalleryUpload(models.Model)

答案 1 :(得分:1)

for root, dirs, files in os.walk(file_path):

file_path指的是zip文件。不是directory因此os.walk不返回任何内容

相关问题