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

如何在Flask项目的HTML中使用Python变量展示图片?

正确实现方案

1. 后端(server.py)修复与优化

确保生成的base64字符串包含浏览器可识别的Data URI前缀,正确传递模板变量,并新增接口支持动态获取图表:

from flask import Flask, render_template, Response
import matplotlib.pyplot as plt
import seaborn as sns
import io
import base64
import random

app = Flask(__name__)

def generate_plot():
    # 模拟后续的动态数据(可替换为URL获取的真实数据)
    x = range(10)
    y = [random.randint(1, 20) for _ in x]
    
    # 创建Seaborn图表
    plt.figure(figsize=(6, 4))
    sns.lineplot(x=x, y=y)
    plt.title("实时更新图表")
    
    # 写入IO缓冲区
    img_buffer = io.BytesIO()
    plt.savefig(img_buffer, format='png', bbox_inches='tight')
    img_buffer.seek(0)
    
    # 转换为带前缀的base64字符串
    img_base64 = base64.b64encode(img_buffer.getvalue()).decode('utf-8')
    img_data = f"data:image/png;base64,{img_base64}"
    
    plt.close()  # 释放Matplotlib资源,避免内存泄漏
    return img_data

@app.route('/')
def index():
    img_data = generate_plot()
    return render_template('index.html', img_data=img_data)

# 供前端动态获取图表数据的接口
@app.route('/get_plot')
def get_plot():
    img_data = generate_plot()
    return Response(img_data, mimetype='text/plain')

if __name__ == '__main__':
    app.run(debug=True)

2. 前端(index.html)修复与自动更新

使用原生JS实现无刷新局部更新,确保图片正确渲染:

<!DOCTYPE html>
<html>
<head>
    <title>实时图表</title>
</head>
<body>
    <img id="dynamic-chart" src="{{ img_data }}" alt="实时更新图表">
    
    <script>
        // 每500毫秒更新一次图表
        setInterval(() => {
            fetch('/get_plot')
                .then(res => res.text())
                .then(data => {
                    document.getElementById('dynamic-chart').src = data;
                });
        }, 500);
    </script>
</body>
</html>

核心问题排查与注意事项

  • 缺失Data URI前缀:直接返回的base64编码无法被浏览器识别为图片,必须添加data:image/png;base64,前缀。
  • Matplotlib资源泄漏:每次生成图表后必须调用plt.close(),否则会累积大量未释放的图表对象。
  • 模板变量语法错误:Flask模板中变量需用双大括号{{ img_data }},而非单大括号。
  • 整页刷新弊端:使用AJAX局部更新避免页面闪烁,同时更适配后续基于URL动态获取数据的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 22:27:29