将ZipFile对象存储到Django数据库中

时间:2014-02-13 15:10:10

标签: python django zip

我认为我遇到的问题非常罕见,因为我似乎无法在这里或谷歌上找到答案。
我有几张图片存储在我的数据库中,为了提供这些图片,我想压缩它们,存储在数据库中创建的ZipFile,该数据库有一个AmazonS3存储作为后端。更重要的是,所有这些操作都是在Celery管理的后台任务中完成的。现在......这是我写的代码:

zipname = "{}.zip".format(reporting.title)

with ZipFile(zipname, 'w') as zf:
    # Here is the zipfile generation. It quite doesn't matter anyway since this works fine.
    reporting = Reporting.objects.get(pk=reporting_id)
    reporting.pictures_archive = zf
    reporting.save()

我收到了错误:*** AttributeError: 'ZipFile' object has no attribute '_committed'
所以我试着用这种方式将zipfile转换为Django文件:zf = File(zf)但它返回一个空对象。

任何人都可以帮助我吗?我有点卡住......

1 个答案:

答案 0 :(得分:1)

这有点像我想象的那么复杂。 (这可以解释为什么没有人在互联网上问这个问题我猜) 使用Python 3.3,您的字符串是unicode,您主要使用unicode对象。文件需要字节数据才能正常工作,所以这是解决方案:

zipname = "{}.zip".format(reporting.id, reporting.title)

with ZipFile(zipname, 'w') as zf:
    # Generating the ZIP ! 

reporting = Reporting.objects.get(pk=reporting_id)
reporting.pictures_archive.delete()
reporting.pictures_archive = File(open(zipname, "rb"))
reporting.save()
相关问题