Python检查Azure指定Blob是否存在并实现安全下载
问题:检查Azure Blob是否存在后再下载对应图片文件
在Azure存储容器的topview目录下存储了命名格式为<ID>_topview.png的图片文件,需要编写Python脚本依据给定的ID列表仅下载Azure中存在的对应图片。现有代码在目标Blob不存在时会抛出错误,尝试使用blob_client.exist()方法无效。
现有实现代码:
blob_service_client = BlobServiceClient.from_connection_string(imagedata_acc_string) container_client = blob_service_client.get_container_client(imagedata_acc_container) topviewfilepath = "gt" + "/" + id + "_topview.png" # blobfilepath = "topview/" + id + "_topview.png" blob_client = container_client.get_blob_client(blobfilepath) with open(topviewfilepath, "wb") as data: myblob = blob_client.download_blob() myblob.readinto(data)
解决方案
方法一:使用正确的exists()方法检查Blob存在性
你之前使用的exist()是拼写错误,Azure Blob Storage Python SDK中BlobClient的正确方法是exists()(末尾带s),该方法会发送HEAD请求验证Blob是否存在,返回布尔值。
修改后的代码:
from azure.storage.blob import BlobServiceClient # 初始化客户端 blob_service_client = BlobServiceClient.from_connection_string(imagedata_acc_string) container_client = blob_service_client.get_container_client(imagedata_acc_container) # 替换为实际的ID列表 id_list = ["id_001", "id_002", "id_003"] for id in id_list: topviewfilepath = f"gt/{id}_topview.png" blobfilepath = f"topview/{id}_topview.png" blob_client = container_client.get_blob_client(blobfilepath) # 检查Blob是否存在 if blob_client.exists(): with open(topviewfilepath, "wb") as data: myblob = blob_client.download_blob() myblob.readinto(data) print(f"已下载:{blobfilepath}") else: print(f"Blob不存在,跳过:{blobfilepath}")
方法二:捕获异常实现无感知跳过
如果需要减少额外的请求次数,可以直接尝试下载操作,当Blob不存在时捕获ResourceNotFoundError异常,这种方式避免了单独的存在性检查请求,适合批量处理场景。
代码示例:
from azure.storage.blob import BlobServiceClient, ResourceNotFoundError # 初始化客户端 blob_service_client = BlobServiceClient.from_connection_string(imagedata_acc_string) container_client = blob_service_client.get_container_client(imagedata_acc_container) # 替换为实际的ID列表 id_list = ["id_001", "id_002", "id_003"] for id in id_list: topviewfilepath = f"gt/{id}_topview.png" blobfilepath = f"topview/{id}_topview.png" blob_client = container_client.get_blob_client(blobfilepath) try: with open(topviewfilepath, "wb") as data: myblob = blob_client.download_blob() myblob.readinto(data) print(f"已下载:{blobfilepath}") except ResourceNotFoundError: print(f"Blob不存在,跳过:{blobfilepath}")
内容的提问来源于stack exchange,提问作者Sulphur
相关产品推荐
相关产品推荐

