예제 #1
0
def extractPackageContent(treeRoot, zip_blob):
    """
        Extract package content into ZOB Tree
    """
    zipfile = ZipFile(zip_blob.open('r'))
    parent_dict = {}
    for path in sorted(zipfile.namelist()):
        if path.endswith('/'):
            # create directory
            path = path[:-1]
            foldername = path.split(os.sep)[-1]
            parent_folder_name = '/'.join(path.split(os.sep)[:-1])
            parent = parent_dict[
                parent_folder_name] if parent_folder_name in parent_dict else treeRoot
            parent.insert(foldername, OOBTree())
            parent_dict[path] = parent[foldername]
        else:
            # create file
            filename = path.split(os.sep)[-1]
            parent_folder_name = '/'.join(path.split(os.sep)[:-1])
            parent = parent_dict[
                parent_folder_name] if parent_folder_name in parent_dict else treeRoot
            data = zipfile.read(path)
            blob = BlobWrapper(get_contenttype(filename=filename))
            file_obj = blob.getBlob().open('w')
            file_obj.write(data)
            file_obj.close()
            blob.setFilename(filename)
            parent.insert(filename, blob)
예제 #2
0
파일: document.py 프로젝트: plomino/Plomino
    def setfile(
        self,
        submittedValue,
        filename='',
        overwrite=False,
        contenttype=''
    ):
        """ Store `submittedValue` (assumed to be a file) as a blob (or FSS).

        The name is normalized before storing. Return the normalized name and
        the guessed content type. (The `contenttype` parameter is ignored.)
        """
        # TODO: does the `contenttype` parameter exist for BBB?
        # If so, mention it. If not, can it go?
        if filename == '':
            filename = submittedValue.filename
        if filename:
            if """\\""" in filename:
                filename = filename.split("\\")[-1]
            filename = '.'.join(
                [normalizeString(s, encoding='utf-8')
                    for s in filename.split('.')])
            if overwrite and filename in self.objectIds():
                self.deletefile(filename)
            try:
                self._checkId(filename)
            except BadRequest:
                #
                # If filename is a reserved id, we rename it
                #
                # Rather than risk dates going back in time when timezone is
                # changed, always use UTC. I.e. here we care more about
                # ordering and uniqueness than about the time (which can be
                # found elsewhere on the object).
                #
                filename = '%s_%s' % (
                    DateTime().toZone('UTC').strftime("%Y%m%d%H%M%S"),
                    filename)

            if (isinstance(submittedValue, FileUpload) or
                    type(submittedValue) == file):
                submittedValue.seek(0)
                contenttype = guessMimetype(submittedValue, filename)
                submittedValue = submittedValue.read()
            elif submittedValue.__class__.__name__ == '_fileobject':
                submittedValue = submittedValue.read()
            blob = BlobWrapper(contenttype)
            file_obj = blob.getBlob().open('w')
            file_obj.write(submittedValue)
            file_obj.close()
            blob.setFilename(filename)
            blob.setContentType(contenttype)
            self._setObject(filename, blob)
            return (filename, contenttype)
        else:
            return (None, "")
예제 #3
0
    def setfile(self,
                submittedValue,
                filename='',
                overwrite=False,
                contenttype=''):
        """ Store `submittedValue` (assumed to be a file) as a blob (or FSS).

        The name is normalized before storing. Return the normalized name and
        the guessed content type. (The `contenttype` parameter is ignored.)
        """
        # TODO: does the `contenttype` parameter exist for BBB?
        # If so, mention it. If not, can it go?
        if filename == '':
            filename = submittedValue.filename
        if filename:
            if """\\""" in filename:
                filename = filename.split("\\")[-1]
            filename = '.'.join([
                normalizeString(s, encoding='utf-8')
                for s in filename.split('.')
            ])
            if overwrite and filename in self.objectIds():
                self.deletefile(filename)
            try:
                self._checkId(filename)
            except BadRequest:
                # if filename is a reserved id, we rename it
                filename = '%s_%s' % (DateTime().toZone('UTC').strftime(
                    "%Y%m%d%H%M%S"), filename)

            if HAS_BLOB:
                if (isinstance(submittedValue, FileUpload)
                        or type(submittedValue) == file):
                    submittedValue.seek(0)
                    contenttype = guessMimetype(submittedValue, filename)
                    submittedValue = submittedValue.read()
                elif submittedValue.__class__.__name__ == '_fileobject':
                    submittedValue = submittedValue.read()
                try:
                    blob = BlobWrapper(contenttype)
                except:  # XXX Except what?
                    # BEFORE PLONE 4.0.1
                    blob = BlobWrapper()
                file_obj = blob.getBlob().open('w')
                file_obj.write(submittedValue)
                file_obj.close()
                blob.setFilename(filename)
                blob.setContentType(contenttype)
                self._setObject(filename, blob)
            else:
                self.manage_addFile(filename, submittedValue)
                contenttype = self[filename].getContentType()
            return (filename, contenttype)
        else:
            return (None, "")
예제 #4
0
    def setfile(self,
                submittedValue,
                filename='',
                overwrite=False,
                contenttype=''):
        """
        """
        if filename == '':
            filename = submittedValue.filename
        if filename != '':
            if """\\""" in filename:
                filename = filename.split("\\")[-1]
            filename = ".".join([
                normalizeString(s, encoding='utf-8')
                for s in filename.split('.')
            ])
            if overwrite and filename in self.objectIds():
                self.deletefile(filename)
            try:
                self._checkId(filename)
            except BadRequest:
                # if filename is a reserved id, we rename it
                filename = DateTime().toZone('UTC').strftime(
                    "%Y%m%d%H%M%S") + "_" + filename

            if (self.getParentDatabase().getStorageAttachments() == True):
                tmpfile = File(filename, filename, submittedValue)
                storage = FileSystemStorage()
                storage.set(filename, self, tmpfile)
                contenttype = storage.get(filename, self).getContentType()
            elif HAS_BLOB:
                if isinstance(submittedValue,
                              FileUpload) or type(submittedValue) == file:
                    submittedValue.seek(0)
                    contenttype = guessMimetype(submittedValue, filename)
                    submittedValue = submittedValue.read()
                try:
                    blob = BlobWrapper(contenttype)
                except:
                    # BEFORE PLONE 4.0.1
                    blob = BlobWrapper()
                file_obj = blob.getBlob().open('w')
                file_obj.write(submittedValue)
                file_obj.close()
                blob.setFilename(filename)
                blob.setContentType(contenttype)
                self._setObject(filename, blob)
            else:
                self.manage_addFile(filename, submittedValue)
                contenttype = self[filename].getContentType()
            return (filename, contenttype)
        else:
            return (None, "")
예제 #5
0
    def upload(self, files, title='', description=''):

        if not self.doc.isDocument():
            return

        #import pdb;pdb.set_trace()

        overwrite = True

        current_files = self.doc.getItem(self.fieldName, {})
        if not current_files:
            current_files = dict()

        #Utile ma pericoloso: se cambio da multi a single elimino tutti i file.. da vedere
        # if not self.multi:
        #     for fileId in current_files.keys():
        #         self.doc.deletefile(fileId)

        if not isinstance(files, list):
            files = [files]

        namechooser = INameChooser(self.doc)
        info = {
            'name': 'File-Name.jpg',
            'title': '',
            'description': '',
            'size': 999999,
            'url': '@@getattachment?',
            'thumbnail_url': '//nohost.org',
            'delete_url': '//nohost.org',
            'delete_type': 'DELETE',
            'field_name': self.fieldName
        }

        results = []

        for item in files:
            if item.filename:

                #            if overwrite and filename in self.objectIds():
                #                self.doc.deletefile(filename)

                contenttype = item.headers.get('Content-Type')
                filename = safe_unicode(item.filename)
                data = item.read()
                id_name = ''
                title = title and title[0] or filename
                #non usata
                description = description and description[0] or ''

                # Get a unique id here
                id_name = namechooser.chooseName(title, self.doc)

                info["name"] = id_name
                info["title"] = title
                info["description"] = description
                info["thumbnail_url"] = self.getIcon(contenttype)
                info["content_type"] = contenttype

                try:
                    blob = BlobWrapper(contenttype)
                except:  # XXX Except what?
                    # BEFORE PLONE 4.0.1
                    blob = BlobWrapper()

                file_obj = blob.getBlob().open('w')
                file_obj.write(data)
                file_obj.close()
                blob.setFilename(id_name)
                blob.setContentType(contenttype)
                info['size'] = blob.get_size()
                self.doc._setObject(id_name, blob)
                results.append(info)

                if self.settings.widget == 'MULTI':
                    current_files[id_name] = contenttype
                    self.doc.setItem(self.fieldName, current_files)
                else:
                    self.doc.setItem(self.fieldName, {id_name: contenttype})

            if results:
                return results
            return False