Matplotlib提示启动的python在Flask应用程序中打开



我正在编写一个Flask应用程序,我使用matplotlib创建一个条形图并保存图像以在浏览器上显示(这很有效(。然而,当我打开带有图像的页面时,python启动器试图打开,然后自行退出,这给了我一个工作说法,即应用程序意外退出。但我的问题不是它没有打开,而是我一开始就不想打开python启动器,因为我只使用matplotlib来创建绘图图像。提醒:在我的Flask页面中,图像显示正确,当我仍在使用浏览器时,python启动器会提示并退出。问题是,我想从一开始就阻止它发射。

我有两个函数,一个返回matplotlib图形,另一个创建图像并将其保存到路线/plot.png上。

这是第一个返回图形的函数(我已经排除了计算值bar_xbar_y的部分,因为我知道第一个函数生成了正确的图形:

def bar_graph(doesn_matter):
fig = plt.gcf()
plt.title("Bar (Spreading of transactions)")
plt.bar(bar_x, bar_y)
plt.show()
return fig

以下是根据matplotlib图生成图像的函数:(purchases是一个总是在变化的全局变量,所显示的图表是基于这个变量的。另一个问题是,当我更改图表时,图表总是重叠的(

@app.route('/plot.png')
@login_required
def plot_png():
global purchases
fig = bar_graph(purchases)
return nocache(fig_response(fig))
def fig_response(fig):
"""Turn a matplotlib Figure into Flask response"""
img_bytes = io.BytesIO()
fig.savefig(img_bytes)
img_bytes.seek(0)
return send_file(img_bytes, mimetype='image/png')
def nocache(response):
"""Add Cache-Control headers to disable caching a response"""
response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0'
return response

最后,如果它是相关的,这就是我在Flask HTML模板中调用图像的方式:

<img src="/plot.png" alt="Plot Results">

这一点最近可能有所改变,但使matplotlib与Flask(或其他无头应用程序(一起工作的标准方法长期以来一直是包括

matplotlib.use('agg')

之后立即

import matplotlib

最新更新