将ZipFile对象存储到Django数据库中 [英] Storing ZipFile Objects into the Django database

查看:114
本文介绍了将ZipFile对象存储到Django数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为我遇到的问题非常罕见,因为我似乎无法在此处或在Google上找到答案。

我在数据库中按顺序存储了几张图片为了提供这些服务,我想压缩它们,将创建的ZipFile存储在数据库中,该数据库具有AmazonS3存储作为后端。更重要的是,所有这些操作都是在Celery管理的后台任务中完成的。现在...这是我编写的代码:

The problem I have is quite uncommon I think, because I didn't seem to be able to find an answer on here or on Google.
I have several pictures stored in my database and in order to serve these, I want to zip them, store the ZipFile created in the database which has an AmazonS3 storage as a backend. On more thing, all these operations are done in a background task managed by Celery. Now... Here is the code I wrote :

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'对象没有属性'_committed'

因此,我尝试通过以下方式将zipfile转换为Django文件: zf = File(zf),但它返回一个空对象。

I got the error : *** AttributeError: 'ZipFile' object has no attribute '_committed'
So I tried to cast the zipfile into a Django File this way : zf = File(zf) but it returns an empty object.

有人可以帮我吗?我有点被困住了……

Can anyone help me with that ? I'm kind of stuck...

推荐答案

这有点不像我想的那么复杂。 (我想这可以解释为什么没有人在整个互联网上都问这个问题)。

使用Python 3.3,您的字符串是unicode,而您主要使用unicode对象。文件需要字节数据才能正常工作,因此以下是解决方法:

This was kind of not as complicated as I thought. (Which could explain why no one asked that question all over the internet I guess)
Using Python 3.3, your strings are unicode and you mainly work with unicode objects. File needs bytes data to work correctly so here is the solution :

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()

这篇关于将ZipFile对象存储到Django数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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