Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask matplotlib graphics in template

I have a pretty beginner-question. Is it possible to display dynamically processed matplotlib images (as shown in https://gist.github.com/wilsaj/862153 or https://gist.github.com/rduplain/1641344) directly via render_template(...) or do I have to use app.route('.../')? The aim is to show a customizable (scientific) plot inside a website.

Is there any clean solution if I want to pass an array (or more than one variable) to the plot function?

like image 209
martin_r Avatar asked Dec 06 '13 23:12

martin_r


1 Answers

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!

like image 129
Miguel Avatar answered Oct 17 '22 04:10

Miguel