如何通过Azure App Functions将文件下载/保存到Blob Storage?
针对Azure HTTP触发函数操作Blob Storage的实现方案
方法1:使用Blob输出绑定(推荐,适配Data Factory流水线场景)
该方案无需手动管理Blob连接,函数运行时会自动处理身份验证和读写逻辑,适合简单的上传/更新场景,和Data Factory集成时参数传递更便捷。
- 第一步:修改函数目录下的
function.json,添加Blob输出绑定配置:
{ "type": "blob", "direction": "out", "name": "outputBlob", "path": "目标容器名/{rand-guid}.txt", "connection": "AzureWebJobsStorage" }
其中connection对应函数应用配置里的存储账户连接字符串变量名,默认AzureWebJobsStorage为函数本身的存储账户,也可替换为待操作的目标存储账户的连接字符串变量名。
- 第二步:调整你的Python函数代码,匹配绑定逻辑:
import logging import requests import azure.functions as func # 新增outputBlob参数对应绑定配置 def main(req: func.HttpRequest, outputBlob: func.Out[bytes]) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') name = req.params.get('name') if not name: try: req_body = req.get_json() except ValueError: pass else: name = req_body.get('name') if name: requested_file = requests.get("你的资源下载地址") # 直接将内容写入输出绑定即可,无需手动处理连接逻辑 outputBlob.set(requested_file.content) return func.HttpResponse(f"Hello, {name}. 文件已成功上传到Blob存储。", status_code=200) else: return func.HttpResponse( "请在查询字符串或请求体中传入name参数", status_code=400 )
方法2:使用Azure Blob SDK手动操作(适合复杂自定义场景)
如果需要更灵活的Blob操作(比如判断文件是否存在、遍历目录、删除文件等),可以用官方SDK手动实现逻辑:
- 第一步:在项目的
requirements.txt中添加依赖:
azure-storage-blob==12.19.0 requests
- 第二步:修改函数代码,手动实现Blob连接和上传逻辑:
import logging import requests import os import azure.functions as func from azure.storage.blob import BlobClient def main(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') name = req.params.get('name') # 从函数应用配置中读取存储账户连接字符串 conn_str = os.environ["你的存储连接字符串配置变量名"] if not name: try: req_body = req.get_json() except ValueError: pass else: name = req_body.get('name') if name: requested_file = requests.get("你的资源下载地址") # 初始化Blob客户端,指定目标容器和文件名 blob_client = BlobClient.from_connection_string(conn_str, container_name="目标容器名", blob_name=f"{name}.txt") # 上传内容,overwrite参数控制是否覆盖已有同名文件 blob_client.upload_blob(requested_file.content, overwrite=True) return func.HttpResponse(f"Hello, {name}. 文件已成功上传到Blob存储。", status_code=200) else: return func.HttpResponse( "请在查询字符串或请求体中传入name参数", status_code=400 )
Data Factory集成提示
你可以在Data Factory的Azure Function活动中,把流水线的参数作为请求体传递给HTTP触发函数,函数拿到参数后可以动态指定Blob路径、文件名等属性,满足流水线的动态操作需求。
内容的提问来源于stack exchange,提问作者rarova
相关产品推荐
相关产品推荐

