【问题标题】:Create blob container in azure storage if it does not exists如果不存在,则在 Azure 存储中创建 Blob 容器
【发布时间】:2020-03-28 22:19:38
【问题描述】:

我正在尝试使用 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 容器,但第二次出现错误。

如果 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

【问题讨论】:

    标签: python azure azure-storage azure-blob-storage


    【解决方案1】:

    如果您使用的是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()
    

    【讨论】:

      【解决方案2】:

      如果您查看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

      【讨论】:

      • 感谢您的回答 Gaurav。我正在寻找类似 @​​987654328@ 的函数(在 C# 中可用)docs.microsoft.com/en-us/dotnet/api/…
      • 您给出的建议是实现此目的的替代方法。如果python库不包含CrateIfNotExists()这样的函数,那我试试你的解决方案
      • 我也很惊讶 Python SDK 没有等效的 CreateIfNotExists() 方法。可以在 Github repo 上提交问题吗?
      【解决方案3】:

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

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

      【讨论】:

      • 这个exist() 方法在azure-storage-blob==12.0.0 中是否可用。我正在使用 12.0.0 的版本 azure-storage-blob
      • 最新的sdk中没有去掉这个方法。如果要使用最新的sdk,则必须使用Gaurav Mantri的方式来捕获异常代码。
      • @Prasad Telkikar,如果这些方式你不想用也许你可以用list_containers,然后在for循环中做判断。
      • 今天我将尝试list_containers的方式并将其签入for循环。
      • 你应该知道现在最新的sdk不支持python的这种方法,那么你只需要决定是否可以使用旧的sdk。如果没有,请尝试我所说的其他方法并选择更可接受的方法。
      【解决方案4】:

      类似于@Paolo's 很好的答案,您可以将代码包装在try..catch 块中,如果容器资源已经存在,则捕获azure.core.exceptions.ResourceExistsError 异常。

      这里的区别在于我捕捉到了引发的特定异常,@Paolo's 的答案是捕捉到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 statement 完全忽略异常:

      try:
          # Attempt to create container
          blob_service_client.create_container(container_name)
      
      # Catch exception and ignore it completely
      except ResourceExistsError:
          pass
      

      【讨论】:

        【解决方案5】:

        我们不再需要为此降级 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",
            )
        

        【讨论】:

          【解决方案6】:

          修改 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 Storage Python SDK

          Sample code

          【讨论】:

            猜你喜欢
            • 2013-02-23
            • 2011-02-24
            • 2016-10-16
            • 2020-12-08
            • 2018-11-21
            • 2019-04-04
            • 1970-01-01
            • 2021-06-11
            • 1970-01-01
            相关资源
            最近更新 更多