Flask matplotlib graphics in template Flask matplotlib graphics in template flask flask

Flask matplotlib graphics in template


You have to use two routes and a template to do this.

The route that shows the page will call render_template() using your HTML page template. The template has the HTML for the page, but not the PNG data.

In the place in the template where the PNG image goes you have to insert a <img> element, as if you were trying to display a static image.

The trick is that the src attribute of this image points to a second route. You can generate it using url_for(). For example:

<img src="{{ url_for('mypng', data = some_data) }}">

When the browser receives the HTML it will find the link to the image and load that URL. That will execute the second route in the server.

This second route generates the PNG data and returns it as a response, without a template and setting a content type of image/png so that the browser renders it as an image. This second route will be coded as shown in the two links you referenced.

I hope this helps!