Pra*_*kar 8 python azure azure-storage azure-storage-blobs azure-blob-storage
我正在尝试在 python 中的 azure 存储中创建 blob 容器。我正在使用MSDN提供的文档将 azure blob 存储集成到我的 python 程序中。
这是代码:
# Quick start code goes here
connectStr = <connString>
blobServiceClient = BlobServiceClient.from_connection_string(connectStr)
containerName = "quickstart-azureStorage"
localFileName = "quickstart-1.txt"
blobClient = blobServiceClient.create_container(containerName)
Run Code Online (Sandbox Code Playgroud)
create_container()第一次创建 blob 容器,但第二次给我错误。
如果不存在,我想创建 blob 容器。如果存在,则使用现有的 blob 容器
我正在使用 azure 存储库版本 12.0.0。IEazure-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")
Run Code Online (Sandbox Code Playgroud)
例外:
RequestId:<requestId>
Time:2019-12-04T06:59:03.1459600Z
ErrorCode:ContainerAlreadyExists
Error:None
Run Code Online (Sandbox Code Playgroud)
如果您使用的是azure-storage-blobbefore的版本12.8,那么可能的解决方案是使用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()
Run Code Online (Sandbox Code Playgroud)
如果您正在使用azure-storage-blobafter的版本12.8,那么您可以简单地使用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()
Run Code Online (Sandbox Code Playgroud)
如果您查看 的文档create_container,它指出:
在指定帐户下创建一个新容器。如果同名容器已存在,则操作失败。
克服这个问题的一种可能的解决方案是创建容器并捕获错误。如果容器已经存在,那么您将收到Conflict (409)错误代码。根据此您可以确定容器是否存在。
如果可以选择降级 SDK,则可以使用version 2.1Python Storage SDK。如果容器存在,默认行为是不抛出异常。您可以在此处查看代码create_container:https://github.com/Azure/azure-storage-python/blob/master/azure-storage-blob/azure/storage/blob/baseblobservice.py。
| 归档时间: |
|
| 查看次数: |
9390 次 |
| 最近记录: |