简体   繁体   中英

Storing ZipFile Objects into the Django database

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

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...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM