예제 #1
0
    def handle(self, verbosity, *args, **options):
        self.set_options(**options)
        fixture1 = '{workdir}/fixtures/products-media.json'.format(
            workdir=settings.WORK_DIR)
        fixture2 = '{workdir}/fixtures/products-meta.json'.format(
            workdir=settings.WORK_DIR)
        if os.path.isfile(fixture1) or os.path.isfile(fixture2):
            if self.interactive:
                mesg = """
This will overwrite your workdir for your django-SHOP demo.
Are you sure you want to do this?

Type 'yes' to continue, or 'no' to cancel: 
"""
                if input(mesg) != 'yes':
                    raise CommandError(
                        "Downloading workdir has been cancelled.")
            else:
                self.stdout.write(
                    self.style.WARNING(
                        "Can not override downloaded data in input-less mode.")
                )
                return

        extract_to = os.path.join(settings.WORK_DIR, os.pardir)
        msg = "Downloading workdir and extracting to {}. Please wait ..."
        self.stdout.write(msg.format(extract_to))
        download_url = self.download_url.format(version=self.version)
        response = requests.get(download_url, stream=True)
        zip_ref = zipfile.ZipFile(StringIO(response.content))
        try:
            zip_ref.extractall(extract_to)
        finally:
            zip_ref.close()
    def handle(self, verbosity, *args, **options):
        self.set_options(**options)

        mesg = (
            "\nThis will overwrite your workdir and install a new database for the django-SHOP demo: {tutorial}\n"
            "Are you sure you want to do this?\n\n"
            "Type 'yes' to continue, or 'no' to cancel: ").format(
                tutorial=settings.SHOP_TUTORIAL)
        if self.interactive and input(mesg) != 'yes':
            raise CommandError("Collecting static files cancelled.")

        extract_to = os.path.join(settings.WORK_DIR, os.pardir)
        msg = "Downloading workdir and extracting to {}. Please wait ..."
        self.stdout.write(msg.format(extract_to))
        download_url = self.download_url.format(
            tutorial=settings.SHOP_TUTORIAL, version=__version__)
        response = requests.get(download_url, stream=True)
        zip_ref = zipfile.ZipFile(StringIO(response.content))
        try:
            zip_ref.extractall(extract_to, pwd=self.pwd)
        finally:
            zip_ref.close()

        call_command('migrate')
        fixture = '{workdir}/{tutorial}/fixtures/myshop.json'
        call_command(
            'loaddata',
            fixture.format(workdir=settings.WORK_DIR,
                           tutorial=settings.SHOP_TUTORIAL))
예제 #3
0
파일: zip.py 프로젝트: roadt/mcomix
    def __init__(self, archive):
        super(ZipArchive, self).__init__(archive)
        self.zip = zipfile.ZipFile(archive, 'r')

        # Encryption is supported starting with Python 2.6
        self._encryption_supported = hasattr(self.zip, "setpassword")
        self._password = None
예제 #4
0
def extract_update(update_archive, destination, password=None):
 """Given an update archive, extracts it. Returns the directory to which it has been extracted"""
 with contextlib.closing(zipfile.ZipFile(update_archive)) as archive:
  if password:
   archive.setpassword(password)
  archive.extractall(path=destination)
 logger.debug("Update extracted")
 return destination
예제 #5
0
 def _write_chunk(target_file, data):
     ''' Helper function for writing out zip file chunks.
 '''
     file_to_zip = basename(target_file).replace('.zip', '')
     with contextlib.closing(zipfile.ZipFile(target_file, 'w')) as out_f:
         zip_info = zipfile.ZipInfo(file_to_zip, time.localtime()[0:6])
         zip_info.external_attr = 0777 << 16L
         zip_info.compress_type = zipfile.ZIP_DEFLATED
         out_f.writestr(zip_info, json.dumps(data, indent=2) + '\n')
예제 #6
0
def x():
    zf = czipfile.ZipFile(fn)
    for name in zf.namelist():
        if name.endswith('html'):
            s = zf.read(name)
            targ = Target()
            pp = lxml.etree.XMLParser(target=targ)
            pp.feed(s)
            sys.stdout.write(pp.close().encode('utf-8'))
예제 #7
0
파일: zip.py 프로젝트: roadt/mcomix
def is_py_supported_zipfile(path):
    """Check if a given zipfile has all internal files stored with Python supported compression
    """
    # Use contextlib's closing for 2.5 compatibility
    with closing(zipfile.ZipFile(path, 'r')) as zip_file:
        for file_info in zip_file.infolist():
            if file_info.compress_type not in (zipfile.ZIP_STORED,
                                               zipfile.ZIP_DEFLATED):
                return False
    return True
예제 #8
0
 def clean(self):
     cleaned_data = super(UploadIconsForms, self).clean()
     if 'zip_file' in self.changed_data:
         try:
             zip_ref = zipfile.ZipFile(cleaned_data['zip_file'].file.file,
                                       'r')
             cleaned_data.update(
                 zip(['font_folder', 'config_data'],
                     self.unzip_archive(zip_ref)))
         finally:
             zip_ref.close()
     return cleaned_data
예제 #9
0
 def decompress(self, cmd, path):
     decompath = decompress_name(path)
     if (os.path.isfile(decompath)):
         return decompath
     if cmd == 'unzip':
         z = zipfile.ZipFile(path)
         p = decompath.split('/')
         z.extractall(path=self.path)
         n = z.namelist()[0]
         os.rename('/mnt/' + n, decompath)
     else:
         raise Exception("No Such Decompressor")
     return decompath
예제 #10
0
def EXTRACT_ZIP(s, buff):

   EXTRACT_ZIP = { }
   file_num = 0
   password_required = False

   zf = czipfile.ZipFile(StringIO(buff))

   for z in zf.namelist():

      if file_num >= MAX_FILES:
         zf.close()
         EXTRACT_ZIP['Object_%s' % file_num] = { 'Error' : 'Max number of compressed files reached' }
         return EXTRACT_ZIP

      zi_child = zf.getinfo(z)

      # Test if content is encrypted
      if zi_child.flag_bits & 0x1:
         password_required = True

      CHILD_ZIP = OrderedDict([('Name', zi_child.filename),
                             ('Last modified', datetime(*zi_child.date_time).strftime("%Y-%m-%d %H:%M:%S")),
                             ('Comment', zi_child.comment),
                             ('CRC', hex(zi_child.CRC)),
                             ('Compressed Size', '%s bytes' % zi_child.compress_size),
                             ('Uncompressed Size', '%s bytes' % zi_child.file_size),
                             ('Compress Type', get_compression_method(zi_child.compress_type)),
                             ('Create System', get_system_mapping(zi_child.create_system)),
                             ('Password Required', password_required)])

      if not password_required and zi_child.file_size != 0:

         try:
            f = zf.open(z, 'r')
            CHILD_ZIP['Buffer'] = f.read()
            f.close()
         except:
            CHILD_ZIP['Buffer'] = 'Failed to extract this specific archive. Invalid or corrupt?'

      EXTRACT_ZIP['Object_%s' % file_num] = CHILD_ZIP
   
      file_num += 1

   zf.close()

   return EXTRACT_ZIP
예제 #11
0
def go():
    print("WAT?")
    list(map(pr, b"watttt"))
    old_zfp = zipfile.ZipFile(
        "/media/Storage/Scripts/MangaCMS/czipfile/325.zip", "r")
    old_zfp.setpassword(b"www.mangababy.com")
    fileNs = old_zfp.namelist()
    files = []

    for fileInfo in fileNs:

        fctnt = old_zfp.open(fileInfo).read()
        files.append((fileInfo, fctnt))

    loop = 0
    for fileN, fctnt in files:
        print("fileN, %s, fctnt, %s" % (fileN, len(fctnt)))
        with open("(2)" + fileN, "wb") as fp:
            fp.write(fctnt)
    def handle(self, verbosity, *args, **options):
        self.set_options(**options)
        self.createdb_if_not_exists()
        self.clear_compressor_cache()
        call_command('migrate')

        fixture = '{workdir}/{tutorial}/fixtures/myshop.json'.format(
            workdir=settings.WORK_DIR, tutorial=self.tutorial)

        if self.interactive:
            mesg = (
                "\nThis will overwrite your workdir and install a new database for the django-SHOP demo: {tutorial}\n"
                "Are you sure you want to do this?\n\n"
                "Type 'yes' to continue, or 'no' to cancel: ").format(
                    tutorial=self.tutorial)
            if input(mesg) != 'yes':
                raise CommandError("SHOP initialization cancelled.")
        else:
            if os.path.isfile(fixture):
                self.stdout.write(
                    self.style.WARNING(
                        "Can not override downloaded data in input-less mode.")
                )
                return

        extract_to = os.path.join(settings.WORK_DIR, os.pardir)
        msg = "Downloading workdir and extracting to {}. Please wait ..."
        self.stdout.write(msg.format(extract_to))
        download_url = self.download_url.format(tutorial=self.tutorial,
                                                version=self.version)
        response = requests.get(download_url, stream=True)
        zip_ref = zipfile.ZipFile(StringIO(response.content))
        try:
            zip_ref.extractall(extract_to, pwd=self.pwd)
        finally:
            zip_ref.close()

        call_command('loaddata', fixture)
        call_command('fix_filer_bug_965')
예제 #13
0
파일: unihan.py 프로젝트: yindian/hzlinkdb
    import czipfile as zipfile
except:
    import zipfile
import xml.sax.saxutils
import struct
import traceback


def unichar(i):
    try:
        return unichr(i)
    except ValueError:
        return struct.pack('i', i).decode('utf-32')


_unihan_zip = zipfile.ZipFile(
    os.path.join(os.path.dirname(__file__), 'unihan', 'Unihan.zip'), 'r')


def _read_data(fname, fields=set(), d=None):
    f = _unihan_zip.open(fname)
    if f:
        if d is None:
            d = {}
        if 1 <= len(fields) <= 3:
            s = list(fields)[0]
            t = '\t' + s + '\t'
            tl = len(t)
            buf = f.read()
            p = buf.find(t)
            q = 0
            while p > 0:
예제 #14
0
    def getMutilZip(self):
        global file_size
        global zip_index

        file_size = 0
        dateziplist = []
        if not os.path.exists(self.__temp_path + str(self.__date) + "/"):
            os.makedirs(self.__temp_path + str(self.__date) + "/")
        if self.filelist:
            zip_logname = '{0}-{1}.log.zip'.format(
                self.__temp_path + str(self.__date) + "\\" + self.__file_name,
                str(zip_index))
            zip_wavname = '{0}-{1}.wav.zip'.format(
                self.__temp_path + str(self.__date) + "\\" + self.__file_name,
                str(zip_index))
            self.zip_log = czipfile.ZipFile(zip_logname, 'w',
                                            czipfile.ZIP_DEFLATED)
            self.zip_wav = czipfile.ZipFile(zip_wavname, 'w',
                                            czipfile.ZIP_DEFLATED)
            if self.zip_log:
                dateziplist.append(zip_logname)
            if self.zip_wav:
                dateziplist.append(zip_wavname)
            for file in self.filelist:
                file_size += os.path.getsize(self.__path + file)
                if file.rfind(".log") > 0:
                    if file_size <= PER_DISK_OF_ZIP:
                        self.zip_log.write(self.__path + file, file)
                    else:
                        self.__logger.log_info('Zip:%s 压缩完成' % zip_logname)
                        print 'Zip:%s done' % zip_logname
                        self.zip_log.close()
                        file_size = 0
                        zip_index += 1
                        zip_logname = '{0}-{1}.log.zip'.format(
                            self.__temp_path + str(self.__date) + "\\" +
                            self.__file_name, str(zip_index))
                        self.zip_log = czipfile.ZipFile(
                            zip_logname, 'w', czipfile.ZIP_DEFLATED)
                        if self.zip_log:
                            dateziplist.append(zip_logname)
                elif file.rfind(".wav") > 0:
                    if file_size <= PER_DISK_OF_ZIP:
                        self.zip_wav.write(self.__path + file, file)
                    else:
                        self.__logger.log_info('Zip:%s 压缩完成' % zip_wavname)
                        print 'Zip:%s done' % zip_wavname
                        self.zip_wav.close()
                        file_size = 0
                        zip_index += 1
                        zip_wavname = '{0}-{1}.wav.zip'.format(
                            self.__temp_path + str(self.__date) + "\\" +
                            self.__file_name, str(zip_index))
                        self.zip_wav = czipfile.ZipFile(
                            zip_wavname, 'w', czipfile.ZIP_DEFLATED)
                        if self.zip_wav:
                            dateziplist.append(zip_wavname)
            if file_size != 0:
                self.__logger.log_info('Zip:%s 压缩完成' % zip_logname)
                print 'Zip:%s done' % zip_logname
                self.__logger.log_info('Zip:%s 压缩完成' % zip_wavname)
                print 'Zip:%s done' % zip_wavname
            self.zip_log.close()
            self.zip_wav.close()
            self.zip_dict[self.__date] = copy.deepcopy(dateziplist)
        else:
            return