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

如何在Flask中通过render返回HTML格式的韦恩图?

在Flask中渲染韦恩图到HTML页面

步骤1:安装必要依赖

确保安装生成韦恩图的专用库:

pip install matplotlib matplotlib-venn

步骤2:Flask路由实现

在Flask应用中生成韦恩图,将其转为base64编码后传递给模板(无需额外保存静态文件,避免文件管理麻烦):

from flask import Flask, render_template
import matplotlib.pyplot as plt
from matplotlib_venn import venn2
import io
import base64

app = Flask(__name__)

@app.route('/')
def show_venn():
    # 生成韦恩图
    fig, ax = plt.subplots()
    venn2(subsets=(10, 5, 3), set_labels=('集合A', '集合B'), ax=ax)
    
    # 将图表转为base64编码
    img_buffer = io.BytesIO()
    plt.savefig(img_buffer, format='png', bbox_inches='tight')
    img_buffer.seek(0)
    img_base64 = base64.b64encode(img_buffer.getvalue()).decode('utf-8')
    plt.close(fig)  # 关闭图表释放内存
    
    return render_template('venn.html', venn_img=img_base64)

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

步骤3:HTML模板(templates/venn.html)

在模板中直接嵌入base64格式的图片:

<!DOCTYPE html>
<html>
<head>
    <title>韦恩图展示</title>
</head>
<body>
    <h1>韦恩图示例</h1>
    <img src="data:image/png;base64,{{ venn_img }}" alt="韦恩图">
</body>
</html>

常见问题排查

  • 若调用matplotlib_venn报错,检查库是否安装成功、版本是否兼容
  • 图表显示不全时,保留bbox_inches='tight'参数避免内容被裁剪
  • 务必调用plt.close(fig),防止长期运行导致内存泄漏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 08:06:04