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

如何在Azure Function中将Python生成的图表上传至Azure Blob Storage?

直接将Python图表上传至Azure Blob Storage(无需本地保存)

可以通过内存缓冲区直接存储图表数据,跳过本地文件保存步骤,直接上传至Azure Blob Storage。以下是具体实现方案:

1. 准备依赖

在Azure Function的requirements.txt中添加必要的库:

azure-storage-blob>=12.19.0
matplotlib>=3.7.0  # 若使用matplotlib绘图,根据实际库调整
plotly>=5.15.0     # 若使用plotly绘图,按需添加

2. 核心实现代码

示例1:Matplotlib图表上传

from matplotlib import pyplot as plt
from azure.storage.blob import BlobServiceClient
import io
import os

def main():
    # 1. 生成图表(替换为你的绘图逻辑)
    plt.figure(figsize=(8, 6))
    plt.plot([1, 2, 3, 4], [10, 22, 18, 30])
    plt.title("业务数据趋势图")
    plt.xlabel("时间节点")
    plt.ylabel("数值")

    # 2. 将图表写入内存缓冲区
    buffer = io.BytesIO()
    plt.savefig(buffer, format='png', dpi=100)
    buffer.seek(0)  # 重置缓冲区指针至起始位置,确保后续读取完整数据
    plt.close()  # 关闭图表释放内存资源

    # 3. 连接Blob Storage并上传
    conn_str = os.environ.get("AZURE_STORAGE_CONNECTION_STRING")  # 从应用设置读取连接字符串
    blob_service_client = BlobServiceClient.from_connection_string(conn_str)
    container_client = blob_service_client.get_container_client("your-container-name")
    blob_client = container_client.get_blob_client("charts/20240520-trend.png")  # 自定义Blob路径和名称

    # 执行上传,overwrite=True允许覆盖同名文件
    blob_client.upload_blob(buffer, overwrite=True)

示例2:Plotly图表上传

如果使用Plotly绘图,逻辑类似:

import plotly.express as px
from azure.storage.blob import BlobServiceClient
import io
import os

def main():
    # 1. 生成Plotly图表
    df = px.data.gapminder().query("country == 'China'")
    fig = px.line(df, x="year", y="gdpPercap", title="中国GDP人均趋势")

    # 2. 写入内存缓冲区
    buffer = io.BytesIO()
    fig.write_image(buffer, format='png', width=800, height=600)
    buffer.seek(0)

    # 3. 上传至Blob Storage
    conn_str = os.environ.get("AZURE_STORAGE_CONNECTION_STRING")
    blob_service_client = BlobServiceClient.from_connection_string(conn_str)
    container_client = blob_service_client.get_container_client("your-container-name")
    blob_client = container_client.get_blob_client("charts/china-gdp-trend.png")
    blob_client.upload_blob(buffer, overwrite=True)

3. Azure Function配置注意事项

  • 连接字符串安全存储:不要硬编码连接字符串,将其添加到Azure Function的「应用设置」中,通过os.environ.get读取。
  • 权限配置:确保Function的托管身份(系统分配或用户分配)拥有Blob Storage的Storage Blob Data Contributor角色,避免上传时权限不足。
  • 资源释放:绘图后及时关闭图表(如plt.close()),避免内存泄漏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 08:15:35