Generate image on-the-fly using FLask and matplotlib

Viewed 2663

I would like to plot an image without having to save it in a static folder.

I've got an example posted here by user Messa working just fine:

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

Then in the HTML file:

<img src="/plot.png" alt="my plot">

The result is perfect. I get the image on the fly.

Now I would like to use some parameters like this:

@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

But of course It doesn't work. I'm quite new to Python and I'm still learing a lot of things.

Thanks!

1 Answers

To pass parameters in, it's best to not prefix them to the URI, since that might confuse Flask's route decoding. Instead, if you form the URL like

/plot.png?x=1,2,3,4&y=100,200,300,400

you can pick the args up via request.args. They'll come in as strings, so you'll need to seperate and convert to ints (or floats, if you're using real numbers)

from flask import request

@app.route('/plot.png')
def plot():
    try:
        x_values = [int(x) for x in request.args.get('x','').split(',')]
        y_values = [int(y) for y in request.args.get('y','').split(',')]
    except:
        # malformed 

I have a working example here of a robust way to handle matplotlib dynamically. The general idea is

from flask import send_file

@app.route('/plot.png')
def plot_png():
    fig, ax = plt.subplots()
    draw(ax)
    return fig_response(fig)

def fig_response(fig):
    """Turn a matplotlib Figure into Flask response"""
    img_bytes = BytesIO()
    fig.savefig(img_bytes)
    img_bytes.seek(0)
    return send_file(img_bytes, mimetype='image/png')

where you supply draw(). Take a look at my example, though, since there are some cache headers you'll want to add.

Related