【问题标题】:Stream Files to Zip File in Azure Blob Storage using Python?使用 Python 将文件流式传输到 Azure Blob 存储中的 Zip 文件?
【发布时间】:2021-05-22 00:09:50
【问题描述】:

我在 Python 中遇到以下问题:

我希望在 Blob 存储中创建一个包含来自 URL 数组的文件的 zipfile,但我不想在内存中创建整个 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 库中找到等效的功能。

【问题讨论】:

  • 您找到解决方案了吗?

标签: python azure azure-blob-storage zipfile


【解决方案1】:

试试这个:

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)

【讨论】:

  • 感谢您的帮助!我的问题可能应该更清楚。我想要实现的是永远不要在本地存储中构建 zipfile,而是将文件直接流式传输到位于 blob 存储中的新 zipfile。据我所知,这就是 C# 示例中所完成的。我计划将此脚本作为 Azure 函数运行。
  • @Rawzm,欢迎您,实际上您可以将临时文件保存在 Azure Function 上,它有自己的文件系统,详情请参阅这篇文章:stackoverflow.com/questions/63265669/…。此外,如果 zip 文件大小大于 1.5 GB,则无法将其加载到 Azure 函数内存中,因为函数内存限制为 1.5GB
猜你喜欢
  • 1970-01-01
  • 2013-08-21
  • 2019-10-14
  • 2021-06-20
  • 2021-01-10
  • 2019-12-01
  • 2020-05-20
  • 2021-11-19
  • 2017-01-24
相关资源
最近更新 更多