【问题标题】:Unzip Password Protected Zip file automatically from azure storage?从 Azure 存储中自动解压缩受密码保护的 Zip 文件?
【发布时间】:2020-12-14 13:41:28
【问题描述】:

我只是想知道有没有办法从 Azure 存储中提取受密码保护的 zip 文件。 我尝试使用 python Azure Function 无济于事,但在读取文件位置时遇到问题。

文件是否必须临时存储在共享位置才能实现?

只是在这里寻找一点方向,我可能错过了一步吗?

问候, 詹姆斯

【问题讨论】:

    标签: python azure zip azure-functions


    【解决方案1】:

    Azure blob 存储仅提供存储功能,没有运行环境来执行解压缩操作。所以基本上,我们应该将 .zip 文件下载到 Azure 函数,解压缩并以 .zip 文件 1 个 1 上传文件。

    为了快速测试,我编写了一个 HTTP 触发 Azure 函数演示,该演示使用密码保护解压缩 zip 文件,它适用于本地:

    import azure.functions as func
    import uuid
    import os
    import shutil
    from azure.storage.blob import ContainerClient
    from zipfile import ZipFile
    
    storageAccountConnstr = '<storage account conn str>'
    container = '<container name>'
    
    #define local temp path, on Azure, the path is recommanded under /home 
    tempPathRoot = 'd:/temp/'
    unZipTempPathRoot = 'd:/unZipTemp/'
    
    
    def main(req=func.HttpRequest) -> func.HttpResponse:
        reqBody = req.get_json()
        fileName = reqBody['fileName']
        zipPass =  reqBody['password']
    
        container_client = ContainerClient.from_connection_string(storageAccountConnstr,container)
    
        #download zip file 
        zipFilePath = tempPathRoot + fileName
        with open(zipFilePath, "wb") as my_blob:
           download_stream = container_client.get_blob_client(fileName).download_blob()
           my_blob.write(download_stream.readall())
    
        #unzip to temp folder
        unZipTempPath = unZipTempPathRoot + str(uuid.uuid4())
        with ZipFile(zipFilePath) as zf:
            zf.extractall(path=unZipTempPath,pwd=bytes(zipPass,'utf8'))
    
        #upload all files in temp folder
        for root, dirs, files in os.walk(unZipTempPath):
            for file in files: 
                filePath = os.path.join(root, file)
                destBlobClient = container_client.get_blob_client(fileName + filePath.replace(unZipTempPath,''))
                with open(filePath, "rb") as data:
                    destBlobClient.upload_blob(data,overwrite=True)
        
        #remove all temp files 
        shutil.rmtree(unZipTempPath)
        os.remove(zipFilePath)
    
        return func.HttpResponse("done")
    

    我的容器中的文件:

    结果:

    使用 blob 触发器会更好地执行此操作,因为如果您的 zip 文件很大,则会导致超时错误。

    无论如何,这只是一个演示,向您展示如何做到这一点。

    【讨论】:

    • 非常感谢!!救了我几个星期的头痛……快一个。临时文件位置在部署到 Azure 后是否有效?
    • @user14780013,很高兴知道它很有帮助。 temp path 是 Azure 上的常用文件路径,它始终有效。 Zip 文件在使用后将被删除。
    • @user14780013 顺便说一句,如果 Azure 上不存在临时路径,则应先创建临时路径
    • 还是和以前一样的问题,打开功能“没有这样的文件或目录”。?除了路径“d:/home/temp/test.zip”之外,代码几乎与上面相同。在/home/下创建了两个和上面一样的文件夹?
    • 在Azure函数上,你应该通过命令手动创建这2个路径,例如: mkdir /home/temp ,并在上面的代码中更改路径
    猜你喜欢
    • 1970-01-01
    • 2022-11-09
    • 2023-01-30
    • 2016-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-03
    相关资源
    最近更新 更多