Python zipfile.html() Examples

The following are 6 code examples of zipfile.html(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module zipfile , or try the search function .
Example #1
Source File: __init__.py    From pyqualtrics with Apache License 2.0 6 votes vote down vote up
def getSingleResponseHTML(self, SurveyID, ResponseID, **kwargs):
        """ Return response in html format (generated by Qualtrics)

        https://survey.qualtrics.com/WRAPI/ControlPanel/docs.php#getSingleResponseHTML_2.5

        :param SurveyID:   The response's associated survey ID
        :param ResponseID: The response to get HTML for
        :param kwargs:     Addition parameters
        :return:  html response as a string
        """
        if not self.request("getSingleResponseHTML",
                            SurveyID=SurveyID,
                            ResponseID=ResponseID,
                            **kwargs):
            return None

        return self.json_response["Result"] 
Example #2
Source File: serialization.py    From qupulse with MIT License 6 votes vote down vote up
def __init__(self, root: str='./storage.zip', compression_method: int=zipfile.ZIP_DEFLATED) -> None:
        """Creates a new FilesystemBackend.

        Args:
            root: The path of the zip file in which all data files are stored. (default: "./storage.zip",
                i.e. the current directory)
            compression_method: The compression method/algorithm used to compress data in the zipfile. Accepts
                all values handled by the zipfile module (ZIP_STORED, ZIP_DEFLATED, ZIP_BZIP2, ZIP_LZMA). Please refer
                to the `zipfile docs <https://docs.python.org/3/library/zipfile.html#zipfile.ZIP_STORED>` for more
                information. (default: zipfile.ZIP_DEFLATED)
        Raises:
            NotADirectoryError if root is not a valid path.
        """
        parent, fname = os.path.split(root)
        if not os.path.isfile(root):
            if not os.path.isdir(parent):
                raise NotADirectoryError(
                    "Cannot create a ZipStorageBackend. The parent path {} is not valid.".format(parent)
                )
            z = zipfile.ZipFile(root, "w")
            z.close()
        elif not zipfile.is_zipfile(root):
            raise FileExistsError("Cannot open a ZipStorageBackend. The file {} is not a zip archive.".format(root))
        self._root = root
        self._compression_method = compression_method 
Example #3
Source File: util.py    From fc-python-sdk with MIT License 5 votes vote down vote up
def zip_dir(inputDir, output):
    """
    Zip up a directory and preserve symlinks and empty directories
    Derived from: https://gist.github.com/kgn/610907
    : param inputDir: the input directory that need be archived.
    : param output: the output file-like object to store the archived data.
    """
    zipOut = zipfile.ZipFile(output, 'w', compression=zipfile.ZIP_DEFLATED)

    rootLen = len(inputDir)

    def _archive_dir(parentDirectory):
        contents = os.listdir(parentDirectory)
        # store empty directories
        if not contents:
            # http://www.velocityreviews.com/forums/t318840-add-empty-directory-using-zipfile.html
            archiveRoot = parentDirectory[rootLen:].replace('\\', '/').lstrip('/')
            zipInfo = zipfile.ZipInfo(archiveRoot + '/')
            zipOut.writestr(zipInfo, '')
        for item in contents:
            fullPath = os.path.join(parentDirectory, item)
            if os.path.isdir(fullPath) and not os.path.islink(fullPath):
                _archive_dir(fullPath)
            else:
                archiveRoot = fullPath[rootLen:].replace('\\', '/').lstrip('/')
                if os.path.islink(fullPath):
                    # http://www.mail-archive.com/python-list@python.org/msg34223.html
                    zipInfo = zipfile.ZipInfo(archiveRoot)
                    zipInfo.create_system = 3
                    # long type of hex val of '0xA1ED0000L',
                    # say, symlink attr magic...
                    zipInfo.external_attr = 2716663808
                    zipOut.writestr(zipInfo, os.readlink(fullPath))
                else:
                    #print('faint {0} {1} {2}'.format(rootLen, fullPath, archiveRoot))
                    zipOut.write(fullPath, archiveRoot, zipfile.ZIP_DEFLATED)

    _archive_dir(inputDir)

    zipOut.close() 
Example #4
Source File: output.py    From slither with GNU Affero General Public License v3.0 5 votes vote down vote up
def output_to_json(filename, error, results):
    """

    :param filename: Filename where the json will be written. If None or "-", write to stdout
    :param error: Error to report
    :param results: Results to report
    :param logger: Logger where to log potential info
    :return:
    """
    # Create our encapsulated JSON result.
    json_result = {
        "success": error is None,
        "error": error,
        "results": results
    }

    if filename == "-":
        filename = None

    # Determine if we should output to stdout
    if filename is None:
        # Write json to console
        print(json.dumps(json_result))
    else:
        # Write json to file
        if os.path.isfile(filename):
            logger.info(yellow(f'{filename} exists already, the overwrite is prevented'))
        else:
            with open(filename, 'w', encoding='utf8') as f:
                json.dump(json_result, f, indent=2)


# https://docs.python.org/3/library/zipfile.html#zipfile-objects 
Example #5
Source File: __init__.py    From pyqualtrics with Apache License 2.0 5 votes vote down vote up
def GetResponseExportFile(self, responseExportId):
        """ Retrieve the response export file after the export is complete
        https://api.qualtrics.com/docs/get-response-export-file
        :param responseExportId: The ID given to you after running your Response Export call or URL return by GetResponseExportProgress
        :type responseExportId: str
        :return: open file, can be read using .read() function or passed to csv library etc
        """
        if "https://" in responseExportId:
            url = responseExportId
        else:
            url = "https://survey.qualtrics.com/API/v3/responseexports/%s/file" % responseExportId
        response = self.request3(url, method="get")
        if response is None:
            return None

        try:
            # Python 3.5
            iofile = BytesIO(response.content)
        except:
            # Python 2.7
            iofile = StringIO(response.content)
        try:
            archive = zipfile.ZipFile(iofile)
            # https://docs.python.org/2/library/zipfile.html#zipfile.ZipFile.namelist
            # Assuming there is only one file in zip archive returned by Qualtrics
            fh = archive.open(archive.namelist()[0], mode="r")

            # Converting binary file stream to text stream, so it can be fed to csv module etc
            # Note this may not work for large csv files that do not fit in memory
            # Not sure how typical is that with Qualtrics surveys, though
            fp = io.TextIOWrapper(fh)
        except BadZipfile as e:
            self.last_error_message = str(e)
            return None
        self.last_error_message = None
        return fp 
Example #6
Source File: serde.py    From PySyft-TensorFlow with Apache License 2.0 5 votes vote down vote up
def _detail_keras_model(worker, model_tuple):
    """
    This function converts a serialized model into a local
    model.

    Args:
        modeltuple (bin): serialized obj of Keras model.
        It's a tuple where the first value is the binary of the model.
        The second is the model id.

    Returns:
        tf.keras.models.Model: a deserialized Keras model
    """
    model_ser, model_id = model_tuple
    bio = io.BytesIO(model_ser)
    with TemporaryDirectory() as model_location:
        with zipfile.ZipFile(bio, 'r', zipfile.ZIP_DEFLATED) as model_file:
            # WARNING: zipped archives can potentially deposit extra files onto
            #  the system, although Python's zipfile offers some protection
            #  more info: https://docs.python.org/3/library/zipfile.html#zipfile.ZipFile.extractall
            # TODO: further investigate security, find better option if needed
            model_file.extractall(model_location)
        model = tf.keras.models.load_model(model_location)

    initialize_object(
        hook=syft.tensorflow.hook,
        obj=model,
        owner=worker,
        reinitialize=False,
        id=model_id,
        init_args=[],
        init_kwargs={},
    )

    return model