我正在尝试使用 python 在 azure 存储中创建 blob 容器。我正在使用 MSDN 提供的文档将 azure blob 存储集成到我的 python 程序中。
这是代码:
connectStr = <connString>
blobServiceClient = BlobServiceClient.from_connection_string(connectStr)
containerName = "quickstart-azureStorage"
localFileName = "quickstart-1.txt"
blobClient = blobServiceClient.create_container(containerName)
create_container()
第一次创建 blob 容器,但第二次出现错误。
I want to create blob container if it does not exists. If it exist then use existing blob container
我使用的是 Azure 存储库版本 12.0.0。即azure-storage-blob==12.0.0
我知道我们可以使用下面的代码对该容器中存在的 blob 执行此操作,但我没有找到任何用于创建容器本身的内容。
检查 blob 是否存在:
blobClient = blobServiceClient.get_blob_client(container=containerName, blob=localFileName)
if blobClient:
print("blob already exists")
else:
print("blob not exists")
异常(exception):
RequestId:<requestId>
Time:2019-12-04T06:59:03.1459600Z
ErrorCode:ContainerAlreadyExists
Error:None
最佳答案
如果您使用的是 12.8
之前的 azure-storage-blob
版本,则可能的解决方案是使用 get_container_properties函数,如果容器不存在就会出错。
此解决方案已使用 12.0.0
版本进行了测试。
from azure.storage.blob import ContainerClient
container = ContainerClient.from_connection_string(connectStr, 'foo')
try:
container_properties = container.get_container_properties()
# Container foo exists. You can now use it.
except Exception as e:
# Container foo does not exist. You can now create it.
container.create_container()
<小时/>
如果您使用 12.8
之后的 azure-storage-blob
版本,则只需使用 exist函数,如果容器存在则返回 true,如果容器不存在则返回 false。
此解决方案已使用 12.8.1
版本进行了测试。
from azure.storage.blob import ContainerClient
container = ContainerClient.from_connection_string(connectStr, 'foo')
if container.exists():
# Container foo exists. You can now use it.
else:
# Container foo does not exist. You can now create it.
container.create_container()
关于python - 如果 blob 容器不存在,则在 azure 存储中创建该容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59170504/