【问题标题】:With help of Python, how can I create dynamic subfolder under Azure Blobstorage?在 Python 的帮助下,如何在 Azure Blob Storage 下创建动态子文件夹?
【发布时间】:2022-03-02 04:08:19
【问题描述】:

我正在尝试在 blob 存储下创建一个动态文件夹(当前日期为 mm-dd-yyyy)。我尝试了不同的资源,包括以下资源:How can I safely create a nested directory? 并使用这些指南尝试创建动态文件夹,但失败并出现以下错误:

Container_client2 = blob_service_client.create_container(container_name/folder) 类型错误: / 不支持的操作数类型:“str”和“str”

这是我的代码快照:

import os

from pathlib import Path
from datetime import datetime
# Instantiate a new BlobServiceClient using a connection string
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient 
from azure.core.exceptions import ResourceNotFoundError, ResourceExistsError

today = datetime.now()

try:
    connect_str = os.getenv('AZURE_STORAGE_CONNECTION_STRING')

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

    # Create a unique name for the container
    folder = today.strftime('%m-%d-%Y')
    container_name = '2021' 
    print('Folder Name ---> ' + folder)
   
    # Create the container
    Container_client1 = blob_service_client.get_container_client(container_name)
    Container_client2 = blob_service_client.create_container(container_name/str(folder))
    print ("get Container client---" + str(Container_client1))
    try:
        for blob in Container_client1.list_blobs():
            print("Found blob: ", blob.name)
    except ResourceNotFoundError:
        print("Container not found.")     
finally:
    print ("nothing")

【问题讨论】:

  • 您不能使用“create_container”创建它们,因为 a) 它们不是容器,b) 文件夹在 Blob 存储中不是真实的(请参阅 stackoverflow.com/questions/65912473/… 了解更多信息)。您可以通过在您的 blob 名称前面加上所需的文件夹值来创建(幻觉)它们。

标签: python azure azure-blob-storage blobstorage


【解决方案1】:

Joel Cochran 是正确的,Azure Blob 中没有子文件夹。 Blob 服务基于平面存储方案,而不是分层方案。但是,您可以在 blob 名称中指定字符或字符串分隔符来创建虚拟层次结构。例如,以下列表显示了有效且唯一的 Blob 名称。请注意,字符串可以作为 blob 名称和同一容器中的虚拟目录名称有效:

  • /a
  • /a.txt
  • /a/b
  • /a/b.txt

您可以在枚举 blob 时利用分隔符。

【讨论】:

  • 是的,你们都是对的。那就是我尝试使用Container_client2 = blob_service_client.create_container(container_name/str(folder))
  • 容器名称中不能有'/',它是你在名为'foo'的容器中命名为'bar/file.txt'的blob。这将使文件“file.txt”看起来像位于文件夹 foo 中的文件夹 bar 中。容器名称只能是字母、数字和连字符。
  • 谢谢。我会试试的。感谢您分享您的知识。
猜你喜欢
  • 2020-03-09
  • 2020-02-14
  • 1970-01-01
  • 1970-01-01
  • 2019-10-10
  • 2014-12-30
  • 2018-04-13
  • 2019-12-21
  • 2022-11-02
相关资源
最近更新 更多