Python调用Azure Blob存储报错:ImportError: No module named azure.storage.blob
解决
ImportError: No module named azure.storage.blob 问题 你遇到的问题核心是Azure存储SDK版本迭代带来的模块结构变化,再加上新旧版本包同时安装引发的命名空间冲突。下面是两种可行的解决思路:
方案一:迁移到新版Azure Blob Storage SDK(推荐)
Azure早已将原有的azure-storage整合包拆分为azure-storage-blob、azure-storage-file等独立包,旧的BlockBlobService类在新版SDK中已被BlobServiceClient替代。按以下步骤操作即可解决:
- 先卸载旧的整合包,彻底消除版本冲突:
pip uninstall -y azure-storage
- 修改代码为新版SDK的写法:
from azure.storage.blob import BlobServiceClient # 用连接字符串初始化客户端(也可通过account_name和account_key构建) connection_string = "DefaultEndpointsProtocol=https;AccountName=account_name;AccountKey=mykey;EndpointSuffix=core.windows.net" blob_service_client = BlobServiceClient.from_connection_string(connection_string) # 获取目标容器的客户端 container_client = blob_service_client.get_container_client("container") # 下载Blob到本地文件 with open("out-test.csv", "wb") as local_file: blob_data = container_client.download_blob("file").readall() local_file.write(blob_data)
方案二:继续使用旧版SDK(仅用于兼容旧代码)
如果想保留原有BlockBlobService的代码逻辑,需要清理拆分后的独立存储包,只保留旧的azure-storage包:
- 卸载所有拆分的存储相关包:
pip uninstall -y azure-storage-blob azure-storage-common azure-storage-file azure-storage-queue azure-storage-nspkg
- 确认环境中仅保留
azure-storage 0.36.0,此时你原本的代码就能正常运行——因为azure.storage.blob模块会从旧整合包中加载,不再被拆分包的命名空间干扰。
错误根源说明
你同时安装了旧版整合包azure-storage和新版拆分包azure-storage-blob,两者命名空间重叠导致Python查找模块时混乱:新版拆分包的结构不再包含BlockBlobService,而旧整合包的模块又被拆分包覆盖,最终引发导入错误。
内容的提问来源于stack exchange,提问作者ElecHertz
相关产品推荐
相关产品推荐

