You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure新BlobServiceClient替代旧BlockBlobService.get_blob_to_bytes方法咨询

Azure Blob存储SDK v12替代get_blob_to_bytes及BlobClient实例化方案

替代旧版get_blob_to_bytes的方法

在azure-storage-blob v12.x中,BlockBlobService属于v2版API的对象,v12改用BlobClient操作单个Blob,没有直接的get_blob_to_bytes方法,对应的实现是通过download_blob()读取字节流:

from azure.storage.blob import BlobClient

# 用连接字符串实例化BlobClient
blob_client = BlobClient.from_connection_string(
    conn_str="你的存储账户连接字符串",
    container_name="目标容器名",
    blob_name="目标Blob名"
)

# 下载并读取Blob字节
downloader = blob_client.download_blob()
blob_bytes = downloader.readall()

download_blob()返回的StorageStreamDownloader对象,调用readall()即可获取Blob的全部字节数据,和旧版get_blob_to_bytes效果完全一致。

从Queue消息中获取信息实例化BlobClient

从Queue消费消息时,必须从消息内容里拿到Blob的容器名和Blob名(这两个是定位Blob的必要信息)。如果当前Queue消息里没有这些内容,需要修改消息生产者,在发送Queue消息时携带这些信息,比如发送JSON格式的消息:

{"container": "user-uploads", "blob": "2024/05/image.jpg"}

消费消息时解析这些字段,再结合存储账户连接字符串(建议从Azure函数的应用设置中读取,避免硬编码)来实例化BlobClient:

import os
import json
from azure.storage.blob import BlobClient
from azure.storage.queue import QueueClient

# 从环境变量读取存储连接字符串
STORAGE_CONN_STR = os.environ["AZURE_STORAGE_CONNECTION_STRING"]

# 初始化QueueClient
queue_client = QueueClient.from_connection_string(STORAGE_CONN_STR, queue_name="你的队列名")

# 消费消息
for msg in queue_client.receive_messages():
    # 解析Queue消息内容
    msg_data = json.loads(msg.content)
    container_name = msg_data["container"]
    blob_name = msg_data["blob"]
    
    # 创建BlobClient并读取字节
    blob_client = BlobClient.from_connection_string(STORAGE_CONN_STR, container_name, blob_name)
    blob_bytes = blob_client.download_blob().readall()
    
    # 处理业务逻辑...
    
    # 删除已处理的消息
    queue_client.delete_message(msg)

如果Blob存储账户和Queue所在的存储账户不同,需要单独配置Blob存储的连接字符串到应用设置中,然后读取对应的环境变量。

额外提示

  • 不要硬编码连接字符串,通过Azure函数的应用程序设置配置,然后用os.environ读取
  • 如果函数是异步类型,可以使用异步API:await blob_client.download_blob()和await downloader.readall(),提升并发处理能力

内容的提问来源于stack exchange,提问作者otk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 18:45:10