How do I convert a ZipFile object to an object supporting the buffer API?

573 views Asked by At

I have a ZipFile object that I need to convert to an object that will work with the buffer api. Context is that I am trying to use an API that says it takes a file with the type string($binary). How do I do this? I know this is completely wrong, but here is my code:

    def create_extension_zip_file(self, path_to_extension_directory, directory_name):
    zipObj = ZipFile("static_extension.zip", "w")
    with zipObj:
        # Iterate over all the files in directory
        for folderName, subfolders, filenames in os.walk(path_to_extension_directory):
            for filename in filenames:
                # create complete filepath of file in directory
                filePath = os.path.join(folderName, filename)
                with open(filename, 'rb') as file_data:
                    bytes_content = file_data.read()
                # Add file to zip
                zipObj.write(bytes_content, basename(filePath))
    return zipObj
1

There are 1 answers

3
snakecharmerb On BEST ANSWER

Or if the API expects a file-like object, you could pass a BytesIO instance when creating the zipfile and pass that to the API

import io

def create_extension_zip_file(self, path_to_extension_directory, directory_name):
    buf = io.BytesIO()
    zipObj = ZipFile(buf, "w")
    with zipObj:
        # Iterate over all the files in directory
        for folderName, subfolders, filenames in os.walk(path_to_extension_directory):
            for filename in filenames:
                # create complete filepath of file in directory
                filePath = os.path.join(folderName, filename)
                with open(filename, 'rb') as file_data:
                    bytes_content = file_data.read()
                # Add file to zip
                zipObj.write(bytes_content, basename(filePath))
    # Rewind the buffer's file pointer (may not be necessary)
    buf.seek(0)
    return buf

If the API expects a bytes instance, you could just open the zip file in binary mode after it has been written, and pass the bytes .

with open('static_extension.zip', 'rb') as f:
    bytes_ = f.read()