I am wondering if there is a way to upload the zip file to the django web server and put the zip files in the django database WITHOUT accessing the actual file system in the process (e.g. extracting the files in the zip to the tmp directory and then upload them)
Django provides a function to convert a python file to a Django file, so if there is a way to convert a ZipExtFile to a python file, that should be fine.
thanks for the help!
Django Model:
from django.db import models class Foo: file = models.FileField(upload_to='somewhere')
Using:
from zipfile import ZipFile from django.core.exceptions import ValidationError from django.core.files import File from io import BytesIO z = ZipFile('zipFile') istream = z.open('subfile') ostream = BytesIO(istream.read()) tmp = Foo(file=File(ostream)) try: tmp.full_clean() except Validation, e: print e
Output:
{'file': [u'This field cannot be blank.']}
[SOLUTION] Solution using an ugly hack:
As Don Quest correctly points out, file classes such as StringIO or BytesIO should represent the data as a virtual file. However, the Django File constructor accepts only the type of the embedded file and nothing else, although classes like the file would also do the job. The hack is to manually set the variables in Django :: File:
buf = bytesarray(OPENED_ZIP_OBJECT.read(FILE_NAME)) tmp_file = BytesIO(buf) dummy_file = File(tmp_file)
Please continue to comment if you have a better solution (except for a special repository)
guinny
source share