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

如何用Python为Azure Function Blob Trigger实现多输出 无需定义多个outputblob

问题根源

你当前使用的是单个固定路径的输出blob绑定,每次调用outputblob.set()方法都会覆盖data4test2/{name}.xml路径下的同一文件,因此最终仅保留最后一次循环的写入结果。要实现动态输出多个独立blob且无需预定义多个输出绑定参数,直接在代码中调用Azure Blob Storage SDK写入是最高效的方案。

操作步骤

1. 安装依赖

在项目的requirements.txt中添加Azure Blob Storage SDK依赖:

azure-functions
azure-storage-blob

本地开发时可执行pip install azure-storage-blob直接安装。

2. 修改__init__.py代码

import logging
import json
import os
import azure.functions as func
from urllib.request import urlopen
from azure.storage.blob import BlobServiceClient

def main(inputblob: func.InputStream):
    logging.info(f"Python blob trigger function processed blob \n"
                 f"Name: {inputblob.name}\n"
                 f"Blob Size: {inputblob.length} bytes")
    
    # 直接复用已有存储连接字符串配置,无需新增配置项
    connection_string = os.environ["data4test_STORAGE"]
    blob_service_client = BlobServiceClient.from_connection_string(connection_string)
    container_client = blob_service_client.get_container_client("data4test2")

    blob = inputblob.read()
    blob_invoices = json.loads(blob)
    # 提取输入blob的文件名前缀,用于生成规范的输出文件名
    input_file_prefix = inputblob.name.split('/')[-1].replace('.json', '')

    for idx, invoice in enumerate(blob_invoices):
        invoice_url = invoice["invoiceFile"]['url']
        with urlopen(invoice_url) as invoice_stream:
            invoice_content = invoice_stream.read()
            # 每个输出文件按序号命名,确保不会重复覆盖
            output_blob_name = f"{input_file_prefix}_{idx}.xml"
            blob_client = container_client.get_blob_client(output_blob_name)
            # overwrite参数可根据是否允许覆盖同名文件调整
            blob_client.upload_blob(invoice_content, overwrite=True)

3. 修改function.json配置

移除原来的outputblob绑定项,不需要预定义任何输出绑定,最终配置如下:

{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "name": "inputblob",
      "type": "blobTrigger",
      "direction": "in",
      "path": "data4test1/{name}.json",
      "connection": "data4test_STORAGE"
    }
  ],
  "disabled": false
}

该方案支持任意数量的输出文件,不需要提前定义多个输出绑定参数,可根据业务规则灵活自定义输出blob的名称、存储路径等属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 22:24:04