Python 中使用 Azure Blob 存储

本文介绍如何使用适用于 Python 的 Azure 存储客户端库来上传 blob。 你可以上传 blob,打开 blob 流并写入流,或者上传带有索引标记的 blob。

Azure 存储中的 Blob 已组织成容器。 必须先创建容器,才能上传 Blob

Blob 服务客户端

from os import getenv
from azure.storage.blob import BlobServiceClient

blob_service_client = BlobServiceClient.from_connection_string(
    getenv("AZURE_STORAGE_CONNECTION_STRING"))

连接字符串

在这里插入图片描述

用于 blob 的方法(文件)

上传 Blob

def upload_blob(filename: str, container: str, data: BinaryIO):
    try:
        blob_client = blob_service_client.get_blob_client(
            container=container, blob=filename)

        blob_client.upload_blob(data)

        print("success")
    except Exception as e:
        print(e.message)

下载 Blob

def download_blob(filename: str, container: str):
    try:
        blob_client = blob_service_client.get_blob_client(
            container=container, blob=filename)

        print(blob_client.download_blob().readall())
    except Exception as e:
        print(e.message)

删除 Blob

def delete_blob(filename: str, container: str):
    try:
        blob_client = blob_service_client.get_blob_client(
            container=container, blob=filename)

        blob_client.delete_blob()

        print("success")
    except Exception as e:
        print(e.message)

容器方法(文件夹)

创建容器

def create_container(container: str):
    try:
        blob_service_client.create_container(container)
        print("success")
    except Exception as e:
        print(e.message)

删除容器

def delete_container(container: str):
    try:
        blob_service_client.delete_container(container)
        print("success")
    except Exception as e:
        print(e.message)

列出容器

def get_containers():
    try:
        containers = blob_service_client.list_containers()
        print([container.name for container in containers])
    except Exception as e:
        print(e.message)

参考资料:

https://blog.csdn.net/qq_33246702/article/details/107319610
https://learn.microsoft.com/zh-cn/azure/storage/blobs/storage-blob-upload-python
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/ZZQHELLO2018/article/details/130257630