python - 使用 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 库中找到等效的功能。
解决方案
尝试这个 :
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)
推荐阅读
- python - 运行 python 脚本时内存不足
- python - Pandas:如何规范化具有多个 JSON 嵌套列表的 JSON 文件?
- spring-boot - Spring Boot 属性 spring.jpa.show-sql 不适用于 Datastore
- javascript - VuePress v.2.0.0-beta.26 使用 v-bind 时出错:可能需要额外的加载器
- javascript - 如何从 Visual Studio 代码命令运行 fs.writeFileSync()?
- scala - 当 UpdateWriteResult 似乎已被弃用时如何使用 update.one()
- unit-testing - 使用 jest 断言窗口对象的值
- django - Django 管理员 | 根据外键关系选择过滤多对多下拉列表
- java - 使用 MediaStore 初始化空目录时遇到问题
- python - OperationalError:“in”附近:语法错误