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

使用Python版Azure Functions定时生成Matplotlib图片存Blob报错求助

解决方案

错误原因

这个TypeError的核心问题是:Azure Functions的Blob输出绑定func.Out[bytes]只接受原始字节数据,但你直接传入了BytesIO对象,类型不兼容导致编码失败。

修改后的完整代码

import datetime
import logging
import pandas as pd
import matplotlib.pyplot as plt
import azure.functions as func
from io import BytesIO
import numpy as np


def main(mytimer: func.TimerRequest, mysecondblob: func.Out[bytes]):
    utc_timestamp = datetime.datetime.utcnow().replace(
        tzinfo=datetime.timezone.utc).isoformat()

    if mytimer.past_due:
        logging.info('The timer is past due!')

    logging.info('Python timer trigger function ran at %s', utc_timestamp)

    t = np.arange(0.01, 10.0, 0.01)
    data1 = np.sin(2 * np.pi * t)

    # 生成正弦波图表
    fig, ax1 = plt.subplots()
    ax1.set_xlabel('time (s)')
    ax1.set_ylabel('sin wave')
    ax1.plot(t, data1)

    # 将图表写入BytesIO流
    image_stream = BytesIO()
    plt.savefig(image_stream, format='png')
    # 重置流指针到起始位置,确保能完整读取内容
    image_stream.seek(0)
    # 读取流中的字节数据,传入Blob输出绑定完成上传
    mysecondblob.set(image_stream.read())
    # 关闭图表释放内存,避免定时任务频繁触发导致内存泄漏
    plt.close(fig)

关键修改点

  • 移除了无意义的with BytesIO() as input_blob:代码块
  • 将mysecondblob.set(image_stream)改为mysecondblob.set(image_stream.read()),把BytesIO对象转为原始字节数据
  • 增加plt.close(fig)释放Matplotlib资源,适合定时任务高频触发场景
  • 显式指定format='png',确保图片格式与Blob路径中的.png后缀匹配

配置验证

你的function.json配置是正确的,只需确认Azure Functions应用的配置中,checkingoutages连接字符串已正确指向目标存储账户即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 15:03:53