ImportError: cannot import name 'BlockBlobService' from 'azure.storage.blob'

ImportError: cannot import name 'BlockBlobService' from 'azure.storage.blob'

我正在尝试将我的 Azure blob 容器中的文本文件从 ANSI 编码转换为 UTF-8 编码,而无需使用 python 在本地下载文件。当我尝试在我的 Python 代码中导入 BlockBlobService 以处理 Azure Blob 存储时,出现以下错误。我相信我已经安装了正确的 python 模块,但可能缺少一些我不知道的其他模块,或者可能是 "not having the correct python module version"。 "pip list" 命令在我的 VM 上显示以下内容。任何帮助都会很好。

pip list Package Version


azure-common         1.1.25
azure-core           1.4.0
azure-nspkg          3.0.2
azure-storage        0.36.0
azure-storage-blob   12.3.0
azure-storage-common 2.1.0
azure-storage-nspkg  3.1.0
bcrypt               3.1.7
certifi              2020.4.5.1
cffi                 1.14.0
chardet              3.0.4
cryptography         2.9
idna                 2.9
isodate              0.6.0
msrest               0.6.13
oauthlib             3.1.0
paramiko             2.7.1
pip                  20.0.2
pycparser            2.20
PyNaCl               1.3.0
python-dateutil      2.8.1
requests             2.23.0
requests-oauthlib    1.3.0
setuptools           41.2.0
six                  1.14.0
urllib3              1.25.8
wheel                0.34.2

如果您的 blob 编码不是 UTF-8,则无法更改它。你说你想用create_blob_from_text来做,所以我想你的文本文件不是UTF-8,你想把它改成UTF-8来上传。

首先你应该知道,如果你的文本文件是UTF-8,你不需要改变任何东西只要上传它,它仍然是UTF-8。但是,如果您的文件不是UTF-8,它不会将其转换为UTF-8,而是使用原始编码将其编码为UTF-8。如果你能理解这一点,你就会知道如何使用 UTF-8 编码将文件上传到 azure blob。

如下所示,我上传了一个编码为 GBK.

的文本文件
txt= open('D:/hello.txt').readline() # GBK Tex

charset = 'UTF-8'
block_blob_service.create_blob_from_text(container_name='test',blob_name='test-gbk.txt',text=txt.encode('ISO-8859-1').decode('GBK'),encoding=charset)

下面是图片,左边是 GBK 编码的原始文件,右边是从 azure blob 下载的文件,它用 'UTF-8'.

编码

更新:我将文本文件打开到 BytesIO,然后使用以下代码上传。你可以忽略 latin-1.

text=open('E:/test.txt',encoding='latin-1').readline()
charset = 'UTF-8'
buf=BytesIO(text.encode('ISO-8859-1').decode('ANSI').encode('UTF-8'))
block_blob_service.create_blob_from_stream(container_name='test',blob_name='test.txt',stream=buf)

Azure-storage-blob, version: 12.3.0 是包含BlobServiceClient 而不是BlockBlobService 的最新版本,所以如果您想使用BlockBlobService,您必须将azure-storage-blob 版本指定为2.1。 0。只是做

pip install azure-storage-blob==2.1.0

这将解决您的问题。