繁体   English   中英

如果不存在,则在 azure 存储中创建 blob 容器

[英]Create blob container in azure storage if it is not exists

我正在尝试在 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)

create_container()第一次创建 blob 容器,但它第二次给我错误。

如果不存在,我想创建 blob 容器。 如果存在,则使用现有的 blob 容器

我正在使用 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")

例外:

RequestId:<requestId>
Time:2019-12-04T06:59:03.1459600Z
ErrorCode:ContainerAlreadyExists
Error:None

对于 12.0.0 版本的库,一个可能的解决方案是使用get_container_properties()函数,如果容器不存在,它将出错:

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.
    print(e)

如果容器不存在,您将看到以下消息:

指定的容器不存在。

错误代码:ContainerNotFound

错误:无

如果您查看create_container的文档,它会指出:

在指定帐户下创建一个新容器。 如果同名容器已经存在,则操作失败。

克服此问题的一种可能解决方案是创建容器并捕获错误。 如果容器已经存在,那么您将收到一个Conflict (409)错误代码。 基于此,您可以确定容器是否存在。

如果可以选择降级 SDK,则可以使用 Python Storage SDK version 2.1 如果容器存在,默认行为是不抛出异常。 您可以在此处查看create_container的代码: https : //github.com/Azure/azure-storage-python/blob/master/azure-storage-blob/azure/storage/blob/baseblobservice.py

我你可以接受低版本的存储sdk,你可以尝试azure-storage-blob==2.1.0 ,有一个exists方法来检查 blob 或容器是否存在。 如果存在,它将返回 true 或返回 false。

在此处输入图片说明

exists方法创建容器后,如果返回false,则返回true就使用容器。

我们不再需要为此降级 sdk。 在 azure-storage-blob 12.8.* 版本中,我们现在在ContainerClient对象上有一个可以使用的exists方法。 [GitHub PR]供参考。

from azure.storage.blob import ContainerClient

# if you prefer async, use below import and prefix async/await as approp. 
# Code remains as is.
# from azure.storage.blob.aio import ContainerClient


def CreateBlobAndContainerIfNeeded(connection_string: str, container_name: str, 
                                   blob_name: str, blob_data):

    container_client = ContainerClient.from_connection_string(
        connection_string, container_name)

    if not container_client.exists():
        container_client.create_container()

    container_client.upload_blob(blob_name, blob_data)


if __name__ == "__main__":
    connection_string = "DefaultEndpointsProtocol=xxxxxxxxxxxxxxx"
    
    CreateBlobAndContainerIfNeeded(
        connection_string,
        "my_container",
        "my_blob_name.dat",
        "Hello Blob",
    )

azure.core.exceptions.ResourceExistsError 出色答案类似,您可以将代码包装在try..catch块中,如果容器资源已存在,则捕获azure.core.exceptions.ResourceExistsError异常。

这里的区别在于我正在捕获引发的特定异常, @Paolo 的答案是捕获Exception ,它是所有异常的基类。 我发现在这种情况下捕获特定异常更清楚,因为它与我试图处理的错误更明显。

此外,如果容器不存在,则azure.storage.blob.BlobServiceClient.create_container将创建容器资源。

from azure.core.exceptions import ResourceExistsError

blob_service_client = BlobServiceClient.from_connection_string(connection_string)

try:
    # Attempt to create container
    blob_service_client.create_container(container_name)

# Catch exception and print error
except ResourceExistsError as error:
    print(error)

# Do something with container

这将从异常中打印此错误:

The specified container already exists.
RequestId:5b70c1d8-701e-0028-3397-3c77d8000000
Time:2020-06-07T06:46:15.1526773Z
ErrorCode:ContainerAlreadyExists
Error:Non

我们也可以使用pass 语句完全忽略异常:

try:
    # Attempt to create container
    blob_service_client.create_container(container_name)

# Catch exception and ignore it completely
except ResourceExistsError:
    pass

修改 Paola 的答案和 Azure Storage Python SDK 教程

connect_str = os.getenv('AZURE_STORAGE_CONNECTION_STRING')

# Create the BlobServiceClient object which will be used to create a container client
blob_service_client = BlobServiceClient.from_connection_string(connect_str)

# Create a unique name for the container
container_name = "foo"

# Create the container
try:
    container_client = blob_service_client.get_container_client(container_name)
    # Container foo exists. You can now use it.
except Exception as e:
    # Container foo does not exist. You can now create it.
    print(e)
    container_client = blob_service_client.create_container(container_name)

模块版本

Name: azure-storage-blob
Version: 12.5.0

参考:

Azure 存储 Python SDK

示例代码

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM