【问题标题】:Error while sending a plot to html in flask将绘图发送到烧瓶中的 html 时出错
【发布时间】:2026-02-04 10:10:02
【问题描述】:

我正在使用烧瓶网络服务器并想要执行以下功能。

  • 将表单数据从 home.html 传递到 python func plot_perf_metric()。
  • 保存表单数据并调用 plot.html。
  • plot.html 调用 output_plot(),它根据保存的表单数据和访问数据库 (mongodb) 中的值生成绘图。
  • plot.html 打印此图。

我目前没有显示图像。

我只得到一个损坏的图片链接。

有人可以帮我吗?

home.html

<!DOCTYPE html>
<html lang="en">
<body>
    <form action="./plot" method="POST">
        <input type="radio" name="perf_metric" value="disk"> Disk <br><br>
        <input type="radio" name="perf_metric" value="memory"> Memory <br><br>
        <input type="radio" name="perf_metric" value="cpu"> CPU <br><br>
        <input type="radio" name="perf_metric" value="egress"> Egress <br><br>
        <input type="radio" name="perf_metric" value="flit"> Flit <br><br>
        <input type="submit" name="submit_plot" value="Send">
    </form>
</body>
</html>

routes.py

from flask import Flask, render_template, send_file
from flask import request,make_response
from pymongo import MongoClient
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
import StringIO
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
import random

app = Flask(__name__)

@app.route('/')
def home():
     return render_template('home.html')


def connect_mongo(text):
    client = MongoClient()
    db = client['mydb']
    collection = db['vload']
    b = list()
    a = list(collection.find())
    for i in range(len(a)):
        b.append(a[i][text])
        return b

@app.route('/output')
def output_plot():
    fig = Figure()
    axis = fig.add_subplot(1, 1, 1)
    b=connect_mongo(plot_perf_metric.text)
    fig = axis.plot(b)
    output = StringIO.StringIO()
    response = make_response(output.getvaluest())
    response.mimetype = 'image/png'
    fig.savefig(output)
    output.seek(0)
    return send_file(output, mimetype='image/png')

@app.route('/plot',methods=['POST'])
def plot_perf_metric():

if(request.form['submit_plot'] == "Send"):
    text = request.form['perf_metric']
    return render_template('plot.html')

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

plot.html

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Plot</title>
</head>
<body>
     <img src="{{ url_for('output_plot') }}" alt="Image Placeholder" height="100">
</body>
</html>

【问题讨论】:

  • 请您给予完整的回击好吗?

标签: python html plot flask flask-wtforms


【解决方案1】:

你需要为output_plot添加一个路由。

@app.route('/output')
def output_plot():
    fig = Figure()
    axis = fig.add_subplot(1, 1, 1)
    b=connect_mongo(plot_perf_metric.text)
    fig = axis.plot(b)
    output = StringIO.StringIO()
    response = make_response(output.getvaluest())
    response.mimetype = 'image/png'
    fig.savefig(output)
    output.seek(0)
    return send_file(output, mimetype='image/png')

【讨论】:

  • 添加路线后,我得到一个破碎的图像,而不是我想要的情节
  • 您的日志中可能有错误。我猜这是plot_perf_metric.text 上的AttributeError。你不能在这样的函数中访问变量。
  • 是的,你的权利。我在网上找到它,您可以在函数之外访问函数中的变量。除了使用全局变量还有其他方法吗?
  • 您可以编写一个返回值的函数。然后,您可以在需要该值的任何地方调用该函数。