首页 > 解决方案 > 使用 Python 将文件流式传输到 Azure Blob 存储中的 Zip 文件?

问题描述

我在 Python 中有以下问题:

我希望在 Blob Storage 中创建一个 zipfile,其中包含来自 URL 数组的文件,但我不想在内存中创建整个 zipfile 然后上传它。理想情况下,我希望将文件流式传输到 blob 存储中的 zipfile。我在 C# https://andrewstevens.dev/posts/stream-files-to-zip-file-in-azure-blob-storage/ 中找到了这篇文章,在 C# https://stackoverflow.com 也找到了这个答案/a/54767264/10550055

我无法在 python azure blob SDK 和 python zipfile 库中找到等效的功能。

标签: pythonazureazure-blob-storagezipfile

解决方案


尝试这个 :

from zipfile import ZipFile
from azure.storage.blob import BlobServiceClient
import os,requests


tempPath = '<temp path>'

if not os.path.isdir(tempPath):
    os.mkdir(tempPath)

zipFileName = 'test.zip'

storageConnstr = ''
container = ''

blob = BlobServiceClient.from_connection_string(storageConnstr).get_container_client(container).get_blob_client(zipFileName)


fileURLs = {'https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg',
'http://1812.img.pp.sohu.com.cn/images/blog/2009/11/18/18/8/125b6560a6ag214.jpg',
'http://513.img.pp.sohu.com.cn/images/blog/2009/11/18/18/27/125b6541abcg215.jpg'}



def download_url(url, save_path, chunk_size=128):
    r = requests.get(url, stream=True)
    with open(save_path, 'wb') as fd:
        for chunk in r.iter_content(chunk_size=chunk_size):
            fd.write(chunk)

zipObj = ZipFile(tempPath + zipFileName, 'w')

#download file and write to zip
for url in fileURLs:
    localFilePath = tempPath + os.path.basename(url)
    download_url(url,localFilePath)
    zipObj.write(localFilePath)
    
zipObj.close()

#upload zip
with open(tempPath + zipFileName, 'rb') as stream:
    blob.upload_blob(stream)

推荐阅读