【问题标题】:Checking if a blob exist in python azure检查python azure中是否存在blob
【发布时间】:2021-04-28 17:53:02
【问题描述】:

由于azure-storage-blob的新更新,blockblob服务折旧

如何检查 blob 是否存在?

此答案不适用于新版本的 azure-storage-blob Faster Azure blob name search with python?

我在 GitHub 上发现了这个问题: https://github.com/Azure/azure-sdk-for-python/issues/12744

【问题讨论】:

    标签: python azure azure-blob-storage


    【解决方案1】:

    2020 年 9 月 10 日发布的版本 12.5.0 现在在新 SDK 中具有 exists 方法。

    例如,

    同步:

    from azure.storage.blob import BlobClient
    
    blob = BlobClient.from_connection_string(conn_str="my_connection_string", container_name="mycontainer", blob_name="myblob")
    exists = blob.exists()
    print(exists)
    

    异步:

    import asyncio
    
    async def check():
        from azure.storage.blob.aio import BlobClient
        blob = BlobClient.from_connection_string(conn_str="my_connection_string", container_name="mycontainer", blob_name="myblob")
        async with blob:
            exists = await blob.exists()
            print(exists)
    

    【讨论】:

    • 这个方法需要将近一秒来检查blob是否存在,有没有更快的方法来实现?
    • 你能试试异步 io 变种吗?更新了答案以包含用于异步的代码 sn-p。
    【解决方案2】:
    from azure.storage.blob import BlobServiceClient
    blob_service_client = BlobServiceClient.from_connection_string(connection_string)
    all_containers = blob_service_client.list_containers()
    print([container['name'] for container in all_containers])
    

    上面的代码将列出所有容器,我们可以从中检查容器是否存在。但请注意,输出是分页的,因此如果您有大量容器,则需要使用延续令牌迭代输出。更多信息请参考:https://github.com/Azure/azure-storage-python/blob/54e60c8c029f41d2573233a70021c4abf77ce67c/azure-storage-blob/azure/storage/blob/baseblobservice.py#L573

    【讨论】:

    • 不鼓励仅使用代码回答。请提供您的答案如何解决问题的摘要,以及为什么它可能比提供的其他答案更可取。
    猜你喜欢
    • 1970-01-01
    • 2013-07-05
    • 2011-02-08
    • 1970-01-01
    • 2012-06-17
    • 2011-10-14
    • 1970-01-01
    • 2020-07-22
    • 2020-08-01
    相关资源
    最近更新 更多