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

Azure Function导入BlobServiceClient失败,发布受阻求解决方案

Azure Function添加Blob存储导入后发布失败的替代Blob下载方案

问题描述

我编写的Azure Function代码原本可以正常发布:

import azure.functions as func
import logging
import os
import tempfile
import subprocess
import json
from pathlib import Path
import glob  

app = func.FunctionApp()


@app.blob_trigger(
    arg_name="myblob",
    path="cssinputbuckettest/{name}.MF4",
    connection="cssdatalakestoragegen2_STORAGE",
)
def BlobTrigger1(myblob: func.InputStream):
    logging.info(
        f"Python blob trigger function processed blob "
        f"Name: {myblob.name} "
        f"Blob Size: {myblob.length} bytes"
    )
...

但为了下载触发Blob之外的其他文件,我在导入语句后添加了from azure.storage.blob import BlobServiceClient, BlobClient,此时发布失败,函数也未被推送。请问是否有其他方式在Azure Function中下载Blob?

替代解决方案

方法1:利用Azure Functions内置Blob客户端类

无需额外导入完整的azure.storage.blob包,直接使用Azure Functions SDK内置的BlobClient类,避免版本冲突问题:

import azure.functions as func
import logging
import os
from azure.functions._blob import BlobClient

def BlobTrigger1(myblob: func.InputStream):
    # 从环境变量获取已配置的存储连接字符串
    conn_str = os.environ["cssdatalakestoragegen2_STORAGE"]
    # 构建目标Blob的客户端实例
    target_blob_client = BlobClient.from_connection_string(
        conn_str=conn_str,
        container_name="目标容器名称",
        blob_name="目标Blob的完整路径/文件名"
    )
    # 下载Blob内容到内存
    blob_content = target_blob_client.download_blob().readall()
    # 也可保存到本地临时文件
    with tempfile.NamedTemporaryFile(mode="wb", delete=False) as temp_file:
        temp_file.write(blob_content)

方法2:修正依赖版本匹配问题

如果一定要使用azure.storage.blob包,需确保本地开发环境与Azure Function运行时的依赖版本一致:

  • 在项目根目录的requirements.txt文件中明确指定兼容的版本,示例:
    azure-functions==1.17.0
    azure-storage-blob==12.19.0
    
  • 本地执行pip install -r requirements.txt安装匹配依赖后,重新发布函数。

方法3:通过托管身份访问Blob存储

若你的Function已启用托管标识,可无需连接字符串,直接通过身份授权访问Blob,更安全且避免包版本问题:

import azure.functions as func
import logging
from azure.identity import DefaultAzureCredential
from azure.storage.blob import BlobServiceClient

def BlobTrigger1(myblob: func.InputStream):
    credential = DefaultAzureCredential()
    # 初始化Blob服务客户端
    blob_service_client = BlobServiceClient(
        account_url="https://你的存储账户名.blob.core.windows.net/",
        credential=credential
    )
    # 获取目标容器和Blob的客户端
    container_client = blob_service_client.get_container_client("目标容器名称")
    blob_client = container_client.get_blob_client("目标Blob的完整路径/文件名")
    # 下载Blob内容
    blob_content = blob_client.download_blob().readall()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 08:02:45