我希望能够绘制一张图片,而不必将其保存在静态文件夹中。
这里用户Messa发布的示例已经可以正常工作:
import io
import random
from flask import Response
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
@app.route('/plot.png')
def plot_png():
fig = create_figure()
output = io.BytesIO()
FigureCanvas(fig).print_png(output)
return Response(output.getvalue(), mimetype='image/png')
def create_figure():
fig = Figure()
axis = fig.add_subplot(1, 1, 1)
xs = range(100)
ys = [random.randint(1, 50) for x in xs]
axis.plot(xs, ys)
return fig
然后在HTML文件中:
<img src="/plot.png" alt="my plot">
结果非常完美,我可以即时获取图像。
现在我想使用一些参数,就像这样:
@app.route('/<x_values_source>/<y_values_source>/plot.png')
def plot_png(x_values_source, y_values_source):
fig = create_figure(x_values_source, y_values_source)
output = io.BytesIO()
FigureCanvas(fig).print_png(output)
return Response(output.getvalue(), mimetype='image/png')
def create_figure(x_values_source, y_values_source):
x_values = function_that_returns_x_values_set(x_values_source)
y_values = function_that_returns_y_values_set(y_values_source)
fig = Figure()
axis = fig.add_subplot(1, 1, 1)
axis.plot(x_values, y_values)
return fig
当然,它不起作用。我对Python还很陌生,仍在学习许多东西。
谢谢!