Merge compressed files code from two modules

This commit is contained in:
Roberto Rosario
2014-06-20 22:45:33 -04:00
parent 45900332c2
commit 9cad8e94e4
3 changed files with 18 additions and 26 deletions

View File

@@ -21,7 +21,14 @@ class NotACompressedFile(Exception):
class CompressedFile(object):
def __init__(self, file_input=None):
if file_input:
self._open(file_input)
try:
# Is it a file like object?
file_input.seek(0)
except AttributeError:
# If not, try open it.
self._open(file_input)
else:
self.file_object = file_input
else:
self._create()
@@ -80,5 +87,14 @@ class CompressedFile(object):
def as_file(self, filename):
return SimpleUploadedFile(name=filename, content=self.write().read())
def children(self):
try:
# Try for a ZIP file
zfobj = zipfile.ZipFile(self.file_object)
filenames = [filename for filename in zfobj.namelist() if not filename.endswith('/')]
return (SimpleUploadedFile(name=filename, content=zfobj.read(filename)) for filename in filenames)
except zipfile.BadZipfile:
raise NotACompressedFile
def close(self):
self.zf.close()

View File

@@ -1,24 +0,0 @@
import zipfile
from django.core.files.uploadedfile import SimpleUploadedFile
class NotACompressedFile(Exception):
pass
class CompressedFile(object):
def __init__(self, file_object):
self.file_object = file_object
def children(self):
try:
# Try for a ZIP file
zfobj = zipfile.ZipFile(self.file_object)
filenames = [filename for filename in zfobj.namelist() if not filename.endswith('/')]
return (SimpleUploadedFile(name=filename, content=zfobj.read(filename)) for filename in filenames)
except zipfile.BadZipfile:
raise NotACompressedFile
# def close(self):
# self.file_object.close()

View File

@@ -10,6 +10,7 @@ from django.contrib.contenttypes import generic
from django.core.exceptions import ValidationError
from django.db import transaction
from common.compressed_files import CompressedFile, NotACompressedFile
from converter.api import get_available_transformations_choices
from converter.literals import DIMENSION_SEPARATOR
from documents.models import Document
@@ -26,7 +27,6 @@ from .literals import (SOURCE_CHOICES, SOURCE_CHOICES_PLURAL,
SOURCE_CHOICE_STAGING, SOURCE_ICON_DISK, SOURCE_ICON_DRIVE,
SOURCE_ICON_CHOICES, SOURCE_CHOICE_WATCH, SOURCE_UNCOMPRESS_CHOICES,
SOURCE_UNCOMPRESS_CHOICE_Y)
from .compressed_file import CompressedFile, NotACompressedFile
logger = logging.getLogger(__name__)